repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
chimkentec/KodiMODo_rep
refs/heads/master
plugin.video.youtube/resources/lib/kodion/impl/mock/__init__.py
88
__author__ = 'bromix' __all__ = []
broferek/ansible
refs/heads/devel
lib/ansible/modules/network/f5/bigip_snat_pool.py
21
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2016, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_snat_pool short_description: Manage SNAT pools on a BIG-IP description: - Manage SNAT pools on a BIG-IP. version_added: 2.3 options: members: description: - List of members to put in the SNAT pool. When a C(state) of present is provided, this parameter is required. Otherwise, it is optional. - The members can be either IP addresses, or names of the SNAT translation objects. type: list aliases: - member description: description: - A general description of the SNAT pool, provided by the user for their benefit. It is optional. type: str version_added: 2.9 name: description: - The name of the SNAT pool. type: str required: True state: description: - Whether the SNAT pool should exist or not. type: str choices: - present - absent default: present partition: description: - Device partition to manage resources on. type: str default: Common version_added: 2.5 notes: - When C(bigip_snat_pool) object is removed it also removes any associated C(bigip_snat_translation) objects. - This is a BIG-IP behavior not module behavior and it only occurs when the C(bigip_snat_translation) objects are also not referenced by another C(bigip_snat_pool). extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) - Wojciech Wypior (@wojtek0806) ''' EXAMPLES = r''' - name: Add the SNAT pool 'my-snat-pool' bigip_snat_pool: name: my-snat-pool state: present members: - 10.10.10.10 - 20.20.20.20 provider: server: lb.mydomain.com user: admin password: secret delegate_to: localhost - name: Change the SNAT pool's members to a single member bigip_snat_pool: name: my-snat-pool state: present member: 30.30.30.30 provider: server: lb.mydomain.com user: admin password: secret delegate_to: localhost - name: Remove the SNAT pool 'my-snat-pool' bigip_snat_pool: name: johnd state: absent provider: server: lb.mydomain.com user: admin password: secret delegate_to: localhost - name: Add the SNAT pool 'my-snat-pool' with a description bigip_snat_pool: name: my-snat-pool state: present members: - 10.10.10.10 - 20.20.20.20 description: A SNAT pool description provider: server: lb.mydomain.com user: admin password: secret delegate_to: localhost ''' RETURN = r''' members: description: - List of members that are part of the SNAT pool. returned: changed and success type: list sample: "['10.10.10.10']" ''' import re import os from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback try: from library.module_utils.network.f5.bigip import F5RestClient from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import fq_name from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import transform_name from library.module_utils.network.f5.ipaddress import is_valid_ip from library.module_utils.network.f5.ipaddress import compress_address from library.module_utils.network.f5.compare import cmp_str_with_none except ImportError: from ansible.module_utils.network.f5.bigip import F5RestClient from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import fq_name from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import transform_name from ansible.module_utils.network.f5.ipaddress import is_valid_ip from ansible.module_utils.network.f5.ipaddress import compress_address from ansible.module_utils.network.f5.compare import cmp_str_with_none class Parameters(AnsibleF5Parameters): api_map = {} updatables = [ 'members', 'description', ] returnables = [ 'members', 'description', ] api_attributes = [ 'members', 'description', ] class ApiParameters(Parameters): pass class ModuleParameters(Parameters): def _clear_member_prefix(self, member): result = os.path.basename(member) return result def _format_member_address(self, member): if len(member.split('%')) > 1: address, rd = member.split('%') if is_valid_ip(address): result = '/{0}/{1}%{2}'.format(self.partition, compress_address(address), rd) return result else: if is_valid_ip(member): address = '/{0}/{1}'.format(self.partition, member) return address else: # names must start with alphabetic character, and can contain hyphens and underscores and numbers # no special characters are allowed pattern = re.compile(r'(?!-)[A-Z-].*(?<!-)$', re.IGNORECASE) if pattern.match(member): address = '/{0}/{1}'.format(self.partition, member) return address raise F5ModuleError( 'The provided member address: {0} is not a valid IP address or snat translation name'.format(member) ) @property def members(self): if self._values['members'] is None: return None result = set() for member in self._values['members']: member = self._clear_member_prefix(member) address = self._format_member_address(member) result.update([address]) return list(result) @property def description(self): if self._values['description'] is None: return None elif self._values['description'] in ['none', '']: return '' return self._values['description'] class Changes(Parameters): def to_return(self): result = {} for returnable in self.returnables: try: result[returnable] = getattr(self, returnable) except Exception: pass result = self._filter_params(result) return result class UsableChanges(Changes): pass class ReportableChanges(Changes): pass class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: return self.__default(param) def __default(self, param): attr1 = getattr(self.want, param) try: attr2 = getattr(self.have, param) if attr1 != attr2: return attr1 except AttributeError: return attr1 @property def members(self): if self.want.members is None: return None if set(self.want.members) == set(self.have.members): return None result = list(set(self.want.members)) return result @property def description(self): result = cmp_str_with_none(self.want.description, self.have.description) return result class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = F5RestClient(**self.module.params) self.want = ModuleParameters(params=self.module.params) self.have = ApiParameters() self.changes = UsableChanges() def _announce_deprecations(self, result): warnings = result.pop('__warnings', []) for warning in warnings: self.module.deprecate( msg=warning['msg'], version=warning['version'] ) def _set_changed_options(self): changed = {} for key in Parameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = UsableChanges(params=changed) def _update_changed_options(self): diff = Difference(self.want, self.have) updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.compare(k) if change is None: continue else: if isinstance(change, dict): changed.update(change) else: changed[k] = change if changed: self.changes = UsableChanges(params=changed) return True return False def exec_module(self): changed = False result = dict() state = self.want.state if state == "present": changed = self.present() elif state == "absent": changed = self.absent() reportable = ReportableChanges(params=self.changes.to_return()) changes = reportable.to_return() result.update(**changes) if self.module._diff and self.have: result['diff'] = self.make_diff() result.update(dict(changed=changed)) self._announce_deprecations(result) return result def _grab_attr(self, item): result = dict() updatables = Parameters.updatables for k in updatables: if getattr(item, k) is not None: result[k] = getattr(item, k) return result def make_diff(self): result = dict(before=self._grab_attr(self.have), after=self._grab_attr(self.want)) return result def present(self): if self.exists(): return self.update() else: return self.create() def absent(self): changed = False if self.exists(): changed = self.remove() return changed def should_update(self): result = self._update_changed_options() if result: return True return False def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.module.check_mode: return True self.update_on_device() return True def create(self): self._set_changed_options() if self.module.check_mode: return True self.create_on_device() if not self.exists(): raise F5ModuleError("Failed to create the SNAT pool") return True def remove(self): if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the SNAT pool") return True def exists(self): uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError: return False if resp.status == 404 or 'code' in response and response['code'] == 404: return False return True def create_on_device(self): params = self.changes.api_params() params['name'] = self.want.name params['partition'] = self.want.partition uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/".format( self.client.provider['server'], self.client.provider['server_port'] ) resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) return response['selfLink'] def update_on_device(self): params = self.changes.api_params() uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) resp = self.client.api.patch(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) def remove_from_device(self): uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) response = self.client.api.delete(uri) if response.status == 200: return True raise F5ModuleError(response.content) def read_current_from_device(self): uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) query = '?expandSubcollections=true' resp = self.client.api.get(uri + query) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) return ApiParameters(params=response) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True argument_spec = dict( name=dict(required=True), members=dict( type='list', aliases=['member'] ), description=dict(), state=dict( default='present', choices=['absent', 'present'] ), partition=dict( default='Common', fallback=(env_fallback, ['F5_PARTITION']) ) ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) self.required_if = [ ['state', 'present', ['members']] ] def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, required_if=spec.required_if ) try: mm = ModuleManager(module=module) results = mm.exec_module() module.exit_json(**results) except F5ModuleError as ex: module.fail_json(msg=str(ex)) if __name__ == '__main__': main()
marcoantoniooliveira/labweb
refs/heads/master
oscar/lib/python2.7/site-packages/django/core/cache/utils.py
114
from __future__ import absolute_import, unicode_literals import hashlib from django.utils.encoding import force_bytes from django.utils.http import urlquote TEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s' def make_template_fragment_key(fragment_name, vary_on=None): if vary_on is None: vary_on = () key = ':'.join([urlquote(var) for var in vary_on]) args = hashlib.md5(force_bytes(key)) return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())
chiragjogi/odoo
refs/heads/8.0
openerp/addons/test_impex/__init__.py
2148
import models
miguelinux/coccinelle
refs/heads/master
python/coccilib/elems.py
2
class Location: def __init__(self, file, current_element, line, column, line_end, column_end): self.file = file self.current_element = current_element self.line = line self.column = column self.line_end = line_end self.column_end = column_end class ElemBase: def __init__(self): pass # class Expression(ElemBase): # def __init__(self, expr): # ElemBase.__init__(self) # self.expr = expr # # def __str__(self): # return self.expr class TermList(ElemBase): def __init__(self, expr, elements): ElemBase.__init__(self) self.expr = expr self.elements = elements def __getitem__(self,n): return self.elements[n] def __str__(self): return self.expr # class Identifier(ElemBase): # def __init__(self, ident): # ElemBase.__init__(self) # self.ident = ident # # def __str__(self): # return self.ident
defzzd/UserDataBase-Heroku
refs/heads/master
venv/Lib/site-packages/pip/_vendor/html5lib/trie/py.py
1323
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type from bisect import bisect_left from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): if not all(isinstance(x, text_type) for x in data.keys()): raise TypeError("All keys must be strings") self._data = data self._keys = sorted(data.keys()) self._cachestr = "" self._cachepoints = (0, len(data)) def __contains__(self, key): return key in self._data def __len__(self): return len(self._data) def __iter__(self): return iter(self._data) def __getitem__(self, key): return self._data[key] def keys(self, prefix=None): if prefix is None or prefix == "" or not self._keys: return set(self._keys) if prefix.startswith(self._cachestr): lo, hi = self._cachepoints start = i = bisect_left(self._keys, prefix, lo, hi) else: start = i = bisect_left(self._keys, prefix) keys = set() if start == len(self._keys): return keys while self._keys[i].startswith(prefix): keys.add(self._keys[i]) i += 1 self._cachestr = prefix self._cachepoints = (start, i) return keys def has_keys_with_prefix(self, prefix): if prefix in self._data: return True if prefix.startswith(self._cachestr): lo, hi = self._cachepoints i = bisect_left(self._keys, prefix, lo, hi) else: i = bisect_left(self._keys, prefix) if i == len(self._keys): return False return self._keys[i].startswith(prefix)
nthiep/global-ssh-server
refs/heads/master
lib/python2.7/site-packages/django/contrib/formtools/tests/__init__.py
95
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import os import pickle import re import warnings from django import http from django.conf import settings from django.contrib.formtools import preview, utils from django.contrib.formtools.wizard import FormWizard from django.test import TestCase from django.test.html import parse_html from django.test.utils import override_settings from django.utils._os import upath from django.utils import unittest from django.contrib.formtools.tests.wizard import * from django.contrib.formtools.tests.forms import * success_string = "Done was called!" success_string_encoded = success_string.encode() class TestFormPreview(preview.FormPreview): def get_context(self, request, form): context = super(TestFormPreview, self).get_context(request, form) context.update({'custom_context': True}) return context def get_initial(self, request): return {'field1': 'Works!'} def done(self, request, cleaned_data): return http.HttpResponse(success_string) @override_settings( TEMPLATE_DIRS=( os.path.join(os.path.dirname(upath(__file__)), 'templates'), ), ) class PreviewTests(TestCase): urls = 'django.contrib.formtools.tests.urls' def setUp(self): super(PreviewTests, self).setUp() # Create a FormPreview instance to share between tests self.preview = preview.FormPreview(TestForm) input_template = '<input type="hidden" name="%s" value="%s" />' self.input = input_template % (self.preview.unused_name('stage'), "%d") self.test_data = {'field1': 'foo', 'field1_': 'asdf'} def test_unused_name(self): """ Verifies name mangling to get uniue field name. """ self.assertEqual(self.preview.unused_name('field1'), 'field1__') def test_form_get(self): """ Test contrib.formtools.preview form retrieval. Use the client library to see if we can sucessfully retrieve the form (mostly testing the setup ROOT_URLCONF process). Verify that an additional hidden input field is created to manage the stage. """ response = self.client.get('/preview/') stage = self.input % 1 self.assertContains(response, stage, 1) self.assertEqual(response.context['custom_context'], True) self.assertEqual(response.context['form'].initial, {'field1': 'Works!'}) def test_form_preview(self): """ Test contrib.formtools.preview form preview rendering. Use the client library to POST to the form to see if a preview is returned. If we do get a form back check that the hidden value is correctly managing the state of the form. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 1, 'date1': datetime.date(2006, 10, 25)}) response = self.client.post('/preview/', self.test_data) # Check to confirm stage is set to 2 in output form. stage = self.input % 2 self.assertContains(response, stage, 1) def test_form_submit(self): """ Test contrib.formtools.preview form submittal. Use the client library to POST to the form with stage set to 3 to see if our forms done() method is called. Check first without the security hash, verify failure, retry with security hash and verify sucess. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 2, 'date1': datetime.date(2006, 10, 25)}) response = self.client.post('/preview/', self.test_data) self.assertNotEqual(response.content, success_string_encoded) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string_encoded) def test_bool_submit(self): """ Test contrib.formtools.preview form submittal when form contains: BooleanField(required=False) Ticket: #6209 - When an unchecked BooleanField is previewed, the preview form's hash would be computed with no value for ``bool1``. However, when the preview form is rendered, the unchecked hidden BooleanField would be rendered with the string value 'False'. So when the preview form is resubmitted, the hash would be computed with the value 'False' for ``bool1``. We need to make sure the hashes are the same in both cases. """ self.test_data.update({'stage':2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash, 'bool1': 'False'}) with warnings.catch_warnings(record=True): response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string_encoded) def test_form_submit_good_hash(self): """ Test contrib.formtools.preview form submittal, using a correct hash """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage':2}) response = self.client.post('/preview/', self.test_data) self.assertNotEqual(response.content, success_string_encoded) hash = utils.form_hmac(TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string_encoded) def test_form_submit_bad_hash(self): """ Test contrib.formtools.preview form submittal does not proceed if the hash is incorrect. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage':2}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, success_string_encoded) hash = utils.form_hmac(TestForm(self.test_data)) + "bad" self.test_data.update({'hash': hash}) response = self.client.post('/previewpreview/', self.test_data) self.assertNotEqual(response.content, success_string_encoded) class FormHmacTests(unittest.TestCase): def test_textfield_hash(self): """ Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas). """ f1 = HashTestForm({'name': 'joe', 'bio': 'Speaking español.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Speaking español. '}) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2) def test_empty_permitted(self): """ Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed. """ f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2) # # FormWizard tests # class TestWizardClass(FormWizard): def get_template(self, step): return 'forms/wizard.html' def done(self, request, cleaned_data): return http.HttpResponse(success_string) class DummyRequest(http.HttpRequest): def __init__(self, POST=None): super(DummyRequest, self).__init__() self.method = POST and "POST" or "GET" if POST is not None: self.POST.update(POST) self._dont_enforce_csrf_checks = True @override_settings( SECRET_KEY="123", TEMPLATE_DIRS=( os.path.join(os.path.dirname(upath(__file__)), 'templates'), ), ) class WizardTests(TestCase): urls = 'django.contrib.formtools.tests.urls' wizard_step_data = ( { '0-name': 'Pony', '0-thirsty': '2', }, { '1-address1': '123 Main St', '1-address2': 'Djangoland', }, { '2-random_crap': 'blah blah', } ) def setUp(self): super(WizardTests, self).setUp() self.save_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.contrib.formtools.wizard') def tearDown(self): super(WizardTests, self).tearDown() self.restore_warnings_state() def test_step_starts_at_zero(self): """ step should be zero for the first form """ response = self.client.get('/wizard1/') self.assertEqual(0, response.context['step0']) def test_step_increments(self): """ step should be incremented when we go to the next page """ response = self.client.post('/wizard1/', {"0-field":"test", "wizard_step":"0"}) self.assertEqual(1, response.context['step0']) def test_bad_hash(self): """ Form should not advance if the hash is missing or bad """ response = self.client.post('/wizard1/', {"0-field":"test", "1-field":"test2", "wizard_step": "1"}) self.assertEqual(0, response.context['step0']) def test_good_hash(self): """ Form should advance if the hash is present and good, as calculated using current method. """ data = {"0-field": "test", "1-field": "test2", "hash_0": { 2: "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", 3: "9355d5dff22d49dbad58e46189982cec649f9f5b", }[pickle.HIGHEST_PROTOCOL], "wizard_step": "1"} response = self.client.post('/wizard1/', data) self.assertEqual(2, response.context['step0']) def test_11726(self): """ Regression test for ticket #11726. Wizard should not raise Http404 when steps are added dynamically. """ reached = [False] that = self class WizardWithProcessStep(TestWizardClass): def process_step(self, request, form, step): if step == 0: if self.num_steps() < 2: self.form_list.append(WizardPageTwoForm) if step == 1: that.assertTrue(isinstance(form, WizardPageTwoForm)) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": { 2: "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", 3: "9355d5dff22d49dbad58e46189982cec649f9f5b", }[pickle.HIGHEST_PROTOCOL], "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) data = {"0-field": "test", "1-field": "test2", "hash_0": { 2: "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", 3: "9355d5dff22d49dbad58e46189982cec649f9f5b", }[pickle.HIGHEST_PROTOCOL], "hash_1": { 2: "1e6f6315da42e62f33a30640ec7e007ad3fbf1a1", 3: "c33142ef9d01b1beae238adf22c3c6c57328f51a", }[pickle.HIGHEST_PROTOCOL], "wizard_step": "2"} self.assertRaises(http.Http404, wizard, DummyRequest(POST=data)) def test_14498(self): """ Regression test for ticket #14498. All previous steps' forms should be validated. """ reached = [False] that = self class WizardWithProcessStep(TestWizardClass): def process_step(self, request, form, step): that.assertTrue(form.is_valid()) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": { 2: "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", 3: "9355d5dff22d49dbad58e46189982cec649f9f5b", }[pickle.HIGHEST_PROTOCOL], "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) def test_14576(self): """ Regression test for ticket #14576. The form of the last step is not passed to the done method. """ reached = [False] that = self class Wizard(TestWizardClass): def done(self, request, form_list): reached[0] = True that.assertTrue(len(form_list) == 2) wizard = Wizard([WizardPageOneForm, WizardPageTwoForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": { 2: "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", 3: "9355d5dff22d49dbad58e46189982cec649f9f5b", }[pickle.HIGHEST_PROTOCOL], "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) def test_15075(self): """ Regression test for ticket #15075. Allow modifying wizard's form_list in process_step. """ reached = [False] that = self class WizardWithProcessStep(TestWizardClass): def process_step(self, request, form, step): if step == 0: self.form_list[1] = WizardPageTwoAlternativeForm if step == 1: that.assertTrue(isinstance(form, WizardPageTwoAlternativeForm)) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": { 2: "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", 3: "9355d5dff22d49dbad58e46189982cec649f9f5b", }[pickle.HIGHEST_PROTOCOL], "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) def grab_field_data(self, response): """ Pull the appropriate field data from the context to pass to the next wizard step """ previous_fields = parse_html(response.context['previous_fields']) fields = {'wizard_step': response.context['step0']} for input_field in previous_fields: input_attrs = dict(input_field.attributes) fields[input_attrs["name"]] = input_attrs["value"] return fields def check_wizard_step(self, response, step_no): """ Helper function to test each step of the wizard - Make sure the call succeeded - Make sure response is the proper step number - return the result from the post for the next step """ step_count = len(self.wizard_step_data) self.assertContains(response, 'Step %d of %d' % (step_no, step_count)) data = self.grab_field_data(response) data.update(self.wizard_step_data[step_no - 1]) return self.client.post('/wizard2/', data) def test_9473(self): response = self.client.get('/wizard2/') for step_no in range(1, len(self.wizard_step_data) + 1): response = self.check_wizard_step(response, step_no)
chrislyon/dj_ds1
refs/heads/master
static/Brython3.2.0-20150701-214155/Lib/test/unittests/test_macurl2path.py
178
import macurl2path import unittest class MacUrl2PathTestCase(unittest.TestCase): def test_url2pathname(self): self.assertEqual(":index.html", macurl2path.url2pathname("index.html")) self.assertEqual(":bar:index.html", macurl2path.url2pathname("bar/index.html")) self.assertEqual("foo:bar:index.html", macurl2path.url2pathname("/foo/bar/index.html")) self.assertEqual("foo:bar", macurl2path.url2pathname("/foo/bar/")) self.assertEqual("", macurl2path.url2pathname("/")) self.assertRaises(RuntimeError, macurl2path.url2pathname, "http://foo.com") self.assertEqual("index.html", macurl2path.url2pathname("///index.html")) self.assertRaises(RuntimeError, macurl2path.url2pathname, "//index.html") self.assertEqual(":index.html", macurl2path.url2pathname("./index.html")) self.assertEqual(":index.html", macurl2path.url2pathname("foo/../index.html")) self.assertEqual("::index.html", macurl2path.url2pathname("../index.html")) def test_pathname2url(self): self.assertEqual("drive", macurl2path.pathname2url("drive:")) self.assertEqual("drive/dir", macurl2path.pathname2url("drive:dir:")) self.assertEqual("drive/dir/file", macurl2path.pathname2url("drive:dir:file")) self.assertEqual("drive/file", macurl2path.pathname2url("drive:file")) self.assertEqual("file", macurl2path.pathname2url("file")) self.assertEqual("file", macurl2path.pathname2url(":file")) self.assertEqual("dir", macurl2path.pathname2url(":dir:")) self.assertEqual("dir/file", macurl2path.pathname2url(":dir:file")) self.assertRaises(RuntimeError, macurl2path.pathname2url, "/") self.assertEqual("dir/../file", macurl2path.pathname2url("dir::file")) if __name__ == "__main__": unittest.main()
MetSystem/PTVS
refs/heads/master
Python/Tests/TestData/DebuggerProject/BreakpointTest.py
18
print('hello')
papouso/odoo
refs/heads/8.0
addons/website_quote/__openerp__.py
303
{ 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Send Professional Quotations', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': """ OpenERP Sale Quote Roller ========================= """, 'author': 'OpenERP SA', 'depends': ['website','sale', 'mail'], 'data': [ 'views/website_quotation.xml', 'views/website_quotation_backend.xml', 'views/report_saleorder.xml', 'data/website_quotation_data.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/website_quotation_demo.xml' ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, }
hampelm/Detroit-Boundaryservice
refs/heads/master
boundaries/configs/production/manage.py
14
#!/usr/bin/env python import os import sys from django.core.management import execute_manager # we want a few paths on the python path # first up we add the root above the application so # we can have absolute paths everywhere python_path = os.path.join( os.path.realpath(os.path.dirname(__file__)), '../../../' ) # we have have a local apps directory apps_path = os.path.join( os.path.realpath(os.path.dirname(__file__)), '../../apps' ) # we add them first to avoid any collisions sys.path.insert(0, python_path) sys.path.insert(0, apps_path) try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
fcelda/tuned
refs/heads/master
tuned/utils/commands.py
2
import tuned.logs import copy import os import tuned.consts as consts from configobj import ConfigObj import re from subprocess import * __all__ = ["write_to_file", "read_file", "execute"] log = tuned.logs.get() def write_to_file(f, data): log.debug("Writing to file: %s < %s" % (f, data)) try: fd = open(f, "w") fd.write(str(data)) fd.close() rc = True except (OSError,IOError) as e: rc = False log.error("Writing to file %s error: %s" % (f, e)) return rc def read_file(f): old_value = "" try: f = open(f, "r") old_value = f.read() f.close() except (OSError,IOError) as e: log.error("Reading %s error: %s" % (f, e)) return old_value def execute(args): retcode = None if not hasattr(execute, "_environment"): execute._environment = os.environ.copy() execute._environment["LC_ALL"] = "C" log.debug("Executing %s." % str(args)) out = "" try: proc = Popen(args, stdout=PIPE, stderr=PIPE, env=execute._environment, close_fds=True) out, err = proc.communicate() retcode = proc.returncode if retcode: err_out = err[:-1] if len(err_out) == 0: err_out = out[:-1] log.error("Executing %s error: %s" % (args[0], err_out)) except (OSError,IOError) as e: retcode = -1 log.error("Executing %s error: %s" % (args[0], e)) return retcode, out # Helper for parsing kernel options like: # [always] never # It will return 'always' def get_active_option(options, dosplit = True): m = re.match(r'.*\[([^\]]+)\].*', options) if m: return m.group(1) if dosplit: return options.split()[0] return options def recommend_profile(): profile = consts.DEFAULT_PROFILE for f in consts.LOAD_DIRECTORIES: config = ConfigObj(os.path.join(f, consts.AUTODETECT_FILE)) for section in reversed(config.keys()): match1 = match2 = True for option in config[section].keys(): value = config[section][option] if value == "": value = r"^$" if option == "virt": # print "ddd" + execute("virt-what")[1] if not re.match(value, execute("virt-what")[1], re.S): match1 = False elif option == "system": if not re.match(value, read_file(consts.SYSTEM_RELEASE_FILE), re.S): match2 = False if match1 and match2: profile = section return profile
rfguri/vimfiles
refs/heads/master
bundle/ycm/third_party/ycmd/third_party/requests/test_requests.py
11
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for Requests.""" from __future__ import division import json import os import pickle import unittest import collections import contextlib import io import requests import pytest from requests.adapters import HTTPAdapter from requests.auth import HTTPDigestAuth, _basic_auth_str from requests.compat import ( Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str, OrderedDict ) from requests.cookies import cookiejar_from_dict, morsel_to_cookie from requests.exceptions import (ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL, MissingSchema, ReadTimeout, Timeout, RetryError) from requests.models import PreparedRequest from requests.structures import CaseInsensitiveDict from requests.sessions import SessionRedirectMixin from requests.models import urlencode from requests.hooks import default_hooks try: import StringIO except ImportError: import io as StringIO try: from multiprocessing.pool import ThreadPool except ImportError: ThreadPool = None if is_py3: def u(s): return s else: def u(s): return s.decode('unicode-escape') @pytest.fixture def httpbin(httpbin): # Issue #1483: Make sure the URL always has a trailing slash httpbin_url = httpbin.url.rstrip('/') + '/' def inner(*suffix): return urljoin(httpbin_url, '/'.join(suffix)) return inner @pytest.fixture def httpsbin_url(httpbin_secure): # Issue #1483: Make sure the URL always has a trailing slash httpbin_url = httpbin_secure.url.rstrip('/') + '/' def inner(*suffix): return urljoin(httpbin_url, '/'.join(suffix)) return inner # Requests to this URL should always fail with a connection timeout (nothing # listening on that port) TARPIT = "http://10.255.255.1" class TestRequests(object): _multiprocess_can_split_ = True def setUp(self): """Create simple data set with headers.""" pass def tearDown(self): """Teardown.""" pass def test_entry_points(self): requests.session requests.session().get requests.session().head requests.get requests.head requests.put requests.patch requests.post def test_invalid_url(self): with pytest.raises(MissingSchema): requests.get('hiwpefhipowhefopw') with pytest.raises(InvalidSchema): requests.get('localhost:3128') with pytest.raises(InvalidSchema): requests.get('localhost.localdomain:3128/') with pytest.raises(InvalidSchema): requests.get('10.122.1.1:3128/') with pytest.raises(InvalidURL): requests.get('http://') def test_basic_building(self): req = requests.Request() req.url = 'http://kennethreitz.org/' req.data = {'life': '42'} pr = req.prepare() assert pr.url == req.url assert pr.body == 'life=42' def test_no_content_length(self, httpbin): get_req = requests.Request('GET', httpbin('get')).prepare() assert 'Content-Length' not in get_req.headers head_req = requests.Request('HEAD', httpbin('head')).prepare() assert 'Content-Length' not in head_req.headers def test_override_content_length(self, httpbin): headers = { 'Content-Length': 'not zero' } r = requests.Request('POST', httpbin('post'), headers=headers).prepare() assert 'Content-Length' in r.headers assert r.headers['Content-Length'] == 'not zero' def test_path_is_not_double_encoded(self): request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare() assert request.path_url == '/get/test%20case' def test_params_are_added_before_fragment(self): request = requests.Request('GET', "http://example.com/path#fragment", params={"a": "b"}).prepare() assert request.url == "http://example.com/path?a=b#fragment" request = requests.Request('GET', "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare() assert request.url == "http://example.com/path?key=value&a=b#fragment" def test_params_original_order_is_preserved_by_default(self): param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1))) session = requests.Session() request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict) prep = session.prepare_request(request) assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1' def test_params_bytes_are_encoded(self): request = requests.Request('GET', 'http://example.com', params=b'test=foo').prepare() assert request.url == 'http://example.com/?test=foo' def test_binary_put(self): request = requests.Request('PUT', 'http://example.com', data=u"ööö".encode("utf-8")).prepare() assert isinstance(request.body, bytes) def test_mixed_case_scheme_acceptable(self, httpbin): s = requests.Session() s.proxies = getproxies() parts = urlparse(httpbin('get')) schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://'] for scheme in schemes: url = scheme + parts.netloc + parts.path r = requests.Request('GET', url) r = s.send(r.prepare()) assert r.status_code == 200, 'failed for scheme {0}'.format(scheme) def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin): r = requests.Request('GET', httpbin('get')) s = requests.Session() s.proxies = getproxies() r = s.send(r.prepare()) assert r.status_code == 200 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin): r = requests.get(httpbin('redirect', '1')) assert r.status_code == 200 assert r.history[0].status_code == 302 assert r.history[0].is_redirect # def test_HTTP_302_ALLOW_REDIRECT_POST(self): # r = requests.post(httpbin('status', '302'), data={'some': 'data'}) # self.assertEqual(r.status_code, 200) def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin): heads = {'User-agent': 'Mozilla/5.0'} r = requests.get(httpbin('user-agent'), headers=heads) assert heads['User-agent'] in r.text assert r.status_code == 200 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin): heads = {'User-agent': 'Mozilla/5.0'} r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads) assert r.status_code == 200 def test_set_cookie_on_301(self, httpbin): s = requests.session() url = httpbin('cookies/set?foo=bar') s.get(url) assert s.cookies['foo'] == 'bar' def test_cookie_sent_on_redirect(self, httpbin): s = requests.session() s.get(httpbin('cookies/set?foo=bar')) r = s.get(httpbin('redirect/1')) # redirects to httpbin('get') assert 'Cookie' in r.json()['headers'] def test_cookie_removed_on_expire(self, httpbin): s = requests.session() s.get(httpbin('cookies/set?foo=bar')) assert s.cookies['foo'] == 'bar' s.get( httpbin('response-headers'), params={ 'Set-Cookie': 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT' } ) assert 'foo' not in s.cookies def test_cookie_quote_wrapped(self, httpbin): s = requests.session() s.get(httpbin('cookies/set?foo="bar:baz"')) assert s.cookies['foo'] == '"bar:baz"' def test_cookie_persists_via_api(self, httpbin): s = requests.session() r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'}) assert 'foo' in r.request.headers['Cookie'] assert 'foo' in r.history[0].request.headers['Cookie'] def test_request_cookie_overrides_session_cookie(self, httpbin): s = requests.session() s.cookies['foo'] = 'bar' r = s.get(httpbin('cookies'), cookies={'foo': 'baz'}) assert r.json()['cookies']['foo'] == 'baz' # Session cookie should not be modified assert s.cookies['foo'] == 'bar' def test_request_cookies_not_persisted(self, httpbin): s = requests.session() s.get(httpbin('cookies'), cookies={'foo': 'baz'}) # Sending a request with cookies should not add cookies to the session assert not s.cookies def test_generic_cookiejar_works(self, httpbin): cj = cookielib.CookieJar() cookiejar_from_dict({'foo': 'bar'}, cj) s = requests.session() s.cookies = cj r = s.get(httpbin('cookies')) # Make sure the cookie was sent assert r.json()['cookies']['foo'] == 'bar' # Make sure the session cj is still the custom one assert s.cookies is cj def test_param_cookiejar_works(self, httpbin): cj = cookielib.CookieJar() cookiejar_from_dict({'foo': 'bar'}, cj) s = requests.session() r = s.get(httpbin('cookies'), cookies=cj) # Make sure the cookie was sent assert r.json()['cookies']['foo'] == 'bar' def test_requests_in_history_are_not_overridden(self, httpbin): resp = requests.get(httpbin('redirect/3')) urls = [r.url for r in resp.history] req_urls = [r.request.url for r in resp.history] assert urls == req_urls def test_history_is_always_a_list(self, httpbin): """ Show that even with redirects, Response.history is always a list. """ resp = requests.get(httpbin('get')) assert isinstance(resp.history, list) resp = requests.get(httpbin('redirect/1')) assert isinstance(resp.history, list) assert not isinstance(resp.history, tuple) def test_headers_on_session_with_None_are_not_sent(self, httpbin): """Do not send headers in Session.headers with None values.""" ses = requests.Session() ses.headers['Accept-Encoding'] = None req = requests.Request('GET', httpbin('get')) prep = ses.prepare_request(req) assert 'Accept-Encoding' not in prep.headers def test_user_agent_transfers(self, httpbin): heads = { 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)' } r = requests.get(httpbin('user-agent'), headers=heads) assert heads['User-agent'] in r.text heads = { 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)' } r = requests.get(httpbin('user-agent'), headers=heads) assert heads['user-agent'] in r.text def test_HTTP_200_OK_HEAD(self, httpbin): r = requests.head(httpbin('get')) assert r.status_code == 200 def test_HTTP_200_OK_PUT(self, httpbin): r = requests.put(httpbin('put')) assert r.status_code == 200 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin): auth = ('user', 'pass') url = httpbin('basic-auth', 'user', 'pass') r = requests.get(url, auth=auth) assert r.status_code == 200 r = requests.get(url) assert r.status_code == 401 s = requests.session() s.auth = auth r = s.get(url) assert r.status_code == 200 def test_connection_error_invalid_domain(self): """Connecting to an unknown domain should raise a ConnectionError""" with pytest.raises(ConnectionError): requests.get("http://doesnotexist.google.com") def test_connection_error_invalid_port(self): """Connecting to an invalid port should raise a ConnectionError""" with pytest.raises(ConnectionError): requests.get("http://localhost:1", timeout=1) def test_LocationParseError(self): """Inputing a URL that cannot be parsed should raise an InvalidURL error""" with pytest.raises(InvalidURL): requests.get("http://fe80::5054:ff:fe5a:fc0") def test_basicauth_with_netrc(self, httpbin): auth = ('user', 'pass') wrong_auth = ('wronguser', 'wrongpass') url = httpbin('basic-auth', 'user', 'pass') old_auth = requests.sessions.get_netrc_auth try: def get_netrc_auth_mock(url): return auth requests.sessions.get_netrc_auth = get_netrc_auth_mock # Should use netrc and work. r = requests.get(url) assert r.status_code == 200 # Given auth should override and fail. r = requests.get(url, auth=wrong_auth) assert r.status_code == 401 s = requests.session() # Should use netrc and work. r = s.get(url) assert r.status_code == 200 # Given auth should override and fail. s.auth = wrong_auth r = s.get(url) assert r.status_code == 401 finally: requests.sessions.get_netrc_auth = old_auth def test_DIGEST_HTTP_200_OK_GET(self, httpbin): auth = HTTPDigestAuth('user', 'pass') url = httpbin('digest-auth', 'auth', 'user', 'pass') r = requests.get(url, auth=auth) assert r.status_code == 200 r = requests.get(url) assert r.status_code == 401 s = requests.session() s.auth = HTTPDigestAuth('user', 'pass') r = s.get(url) assert r.status_code == 200 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin): url = httpbin('digest-auth', 'auth', 'user', 'pass') auth = HTTPDigestAuth('user', 'pass') r = requests.get(url) assert r.cookies['fake'] == 'fake_value' r = requests.get(url, auth=auth) assert r.status_code == 200 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin): url = httpbin('digest-auth', 'auth', 'user', 'pass') auth = HTTPDigestAuth('user', 'pass') s = requests.Session() s.get(url, auth=auth) assert s.cookies['fake'] == 'fake_value' def test_DIGEST_STREAM(self, httpbin): auth = HTTPDigestAuth('user', 'pass') url = httpbin('digest-auth', 'auth', 'user', 'pass') r = requests.get(url, auth=auth, stream=True) assert r.raw.read() != b'' r = requests.get(url, auth=auth, stream=False) assert r.raw.read() == b'' def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin): auth = HTTPDigestAuth('user', 'wrongpass') url = httpbin('digest-auth', 'auth', 'user', 'pass') r = requests.get(url, auth=auth) assert r.status_code == 401 r = requests.get(url) assert r.status_code == 401 s = requests.session() s.auth = auth r = s.get(url) assert r.status_code == 401 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin): auth = HTTPDigestAuth('user', 'pass') url = httpbin('digest-auth', 'auth', 'user', 'pass') r = requests.get(url, auth=auth) assert '"auth"' in r.request.headers['Authorization'] def test_POSTBIN_GET_POST_FILES(self, httpbin): url = httpbin('post') post1 = requests.post(url).raise_for_status() post1 = requests.post(url, data={'some': 'data'}) assert post1.status_code == 200 with open('requirements.txt') as f: post2 = requests.post(url, files={'some': f}) assert post2.status_code == 200 post4 = requests.post(url, data='[{"some": "json"}]') assert post4.status_code == 200 with pytest.raises(ValueError): requests.post(url, files=['bad file data']) def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin): url = httpbin('post') post1 = requests.post(url).raise_for_status() post1 = requests.post(url, data={'some': 'data'}) assert post1.status_code == 200 with open('requirements.txt') as f: post2 = requests.post(url, data={'some': 'data'}, files={'some': f}) assert post2.status_code == 200 post4 = requests.post(url, data='[{"some": "json"}]') assert post4.status_code == 200 with pytest.raises(ValueError): requests.post(url, files=['bad file data']) def test_conflicting_post_params(self, httpbin): url = httpbin('post') with open('requirements.txt') as f: pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})") pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})") def test_request_ok_set(self, httpbin): r = requests.get(httpbin('status', '404')) assert not r.ok def test_status_raising(self, httpbin): r = requests.get(httpbin('status', '404')) with pytest.raises(requests.exceptions.HTTPError): r.raise_for_status() r = requests.get(httpbin('status', '500')) assert not r.ok def test_decompress_gzip(self, httpbin): r = requests.get(httpbin('gzip')) r.content.decode('ascii') def test_unicode_get(self, httpbin): url = httpbin('/get') requests.get(url, params={'foo': 'føø'}) requests.get(url, params={'føø': 'føø'}) requests.get(url, params={'føø': 'føø'}) requests.get(url, params={'foo': 'foo'}) requests.get(httpbin('ø'), params={'foo': 'foo'}) def test_unicode_header_name(self, httpbin): requests.put( httpbin('put'), headers={str('Content-Type'): 'application/octet-stream'}, data='\xff') # compat.str is unicode. def test_pyopenssl_redirect(self, httpsbin_url, httpbin_ca_bundle): requests.get(httpsbin_url('status', '301'), verify=httpbin_ca_bundle) def test_urlencoded_get_query_multivalued_param(self, httpbin): r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz'])) assert r.status_code == 200 assert r.url == httpbin('get?test=foo&test=baz') def test_different_encodings_dont_break_post(self, httpbin): r = requests.post(httpbin('post'), data={'stuff': json.dumps({'a': 123})}, params={'blah': 'asdf1234'}, files={'file': ('test_requests.py', open(__file__, 'rb'))}) assert r.status_code == 200 def test_unicode_multipart_post(self, httpbin): r = requests.post(httpbin('post'), data={'stuff': u('ëlïxr')}, files={'file': ('test_requests.py', open(__file__, 'rb'))}) assert r.status_code == 200 r = requests.post(httpbin('post'), data={'stuff': u('ëlïxr').encode('utf-8')}, files={'file': ('test_requests.py', open(__file__, 'rb'))}) assert r.status_code == 200 r = requests.post(httpbin('post'), data={'stuff': 'elixr'}, files={'file': ('test_requests.py', open(__file__, 'rb'))}) assert r.status_code == 200 r = requests.post(httpbin('post'), data={'stuff': 'elixr'.encode('utf-8')}, files={'file': ('test_requests.py', open(__file__, 'rb'))}) assert r.status_code == 200 def test_unicode_multipart_post_fieldnames(self, httpbin): filename = os.path.splitext(__file__)[0] + '.py' r = requests.Request(method='POST', url=httpbin('post'), data={'stuff'.encode('utf-8'): 'elixr'}, files={'file': ('test_requests.py', open(filename, 'rb'))}) prep = r.prepare() assert b'name="stuff"' in prep.body assert b'name="b\'stuff\'"' not in prep.body def test_unicode_method_name(self, httpbin): files = {'file': open('test_requests.py', 'rb')} r = requests.request( method=u('POST'), url=httpbin('post'), files=files) assert r.status_code == 200 def test_unicode_method_name_with_request_object(self, httpbin): files = {'file': open('test_requests.py', 'rb')} s = requests.Session() req = requests.Request(u("POST"), httpbin('post'), files=files) prep = s.prepare_request(req) assert isinstance(prep.method, builtin_str) assert prep.method == "POST" resp = s.send(prep) assert resp.status_code == 200 def test_custom_content_type(self, httpbin): r = requests.post( httpbin('post'), data={'stuff': json.dumps({'a': 123})}, files={'file1': ('test_requests.py', open(__file__, 'rb')), 'file2': ('test_requests', open(__file__, 'rb'), 'text/py-content-type')}) assert r.status_code == 200 assert b"text/py-content-type" in r.request.body def test_hook_receives_request_arguments(self, httpbin): def hook(resp, **kwargs): assert resp is not None assert kwargs != {} requests.Request('GET', httpbin(), hooks={'response': hook}) def test_session_hooks_are_used_with_no_request_hooks(self, httpbin): hook = lambda x, *args, **kwargs: x s = requests.Session() s.hooks['response'].append(hook) r = requests.Request('GET', httpbin()) prep = s.prepare_request(r) assert prep.hooks['response'] != [] assert prep.hooks['response'] == [hook] def test_session_hooks_are_overridden_by_request_hooks(self, httpbin): hook1 = lambda x, *args, **kwargs: x hook2 = lambda x, *args, **kwargs: x assert hook1 is not hook2 s = requests.Session() s.hooks['response'].append(hook2) r = requests.Request('GET', httpbin(), hooks={'response': [hook1]}) prep = s.prepare_request(r) assert prep.hooks['response'] == [hook1] def test_prepared_request_hook(self, httpbin): def hook(resp, **kwargs): resp.hook_working = True return resp req = requests.Request('GET', httpbin(), hooks={'response': hook}) prep = req.prepare() s = requests.Session() s.proxies = getproxies() resp = s.send(prep) assert hasattr(resp, 'hook_working') def test_prepared_from_session(self, httpbin): class DummyAuth(requests.auth.AuthBase): def __call__(self, r): r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok' return r req = requests.Request('GET', httpbin('headers')) assert not req.auth s = requests.Session() s.auth = DummyAuth() prep = s.prepare_request(req) resp = s.send(prep) assert resp.json()['headers'][ 'Dummy-Auth-Test'] == 'dummy-auth-test-ok' def test_prepare_request_with_bytestring_url(self): req = requests.Request('GET', b'https://httpbin.org/') s = requests.Session() prep = s.prepare_request(req) assert prep.url == "https://httpbin.org/" def test_links(self): r = requests.Response() r.headers = { 'cache-control': 'public, max-age=60, s-maxage=60', 'connection': 'keep-alive', 'content-encoding': 'gzip', 'content-type': 'application/json; charset=utf-8', 'date': 'Sat, 26 Jan 2013 16:47:56 GMT', 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"', 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT', 'link': ('<https://api.github.com/users/kennethreitz/repos?' 'page=2&per_page=10>; rel="next", <https://api.github.' 'com/users/kennethreitz/repos?page=7&per_page=10>; ' ' rel="last"'), 'server': 'GitHub.com', 'status': '200 OK', 'vary': 'Accept', 'x-content-type-options': 'nosniff', 'x-github-media-type': 'github.beta', 'x-ratelimit-limit': '60', 'x-ratelimit-remaining': '57' } assert r.links['next']['rel'] == 'next' def test_cookie_parameters(self): key = 'some_cookie' value = 'some_value' secure = True domain = 'test.com' rest = {'HttpOnly': True} jar = requests.cookies.RequestsCookieJar() jar.set(key, value, secure=secure, domain=domain, rest=rest) assert len(jar) == 1 assert 'some_cookie' in jar cookie = list(jar)[0] assert cookie.secure == secure assert cookie.domain == domain assert cookie._rest['HttpOnly'] == rest['HttpOnly'] def test_cookie_as_dict_keeps_len(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.cookies.RequestsCookieJar() jar.set(key, value) jar.set(key1, value1) d1 = dict(jar) d2 = dict(jar.iteritems()) d3 = dict(jar.items()) assert len(jar) == 2 assert len(d1) == 2 assert len(d2) == 2 assert len(d3) == 2 def test_cookie_as_dict_keeps_items(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.cookies.RequestsCookieJar() jar.set(key, value) jar.set(key1, value1) d1 = dict(jar) d2 = dict(jar.iteritems()) d3 = dict(jar.items()) assert d1['some_cookie'] == 'some_value' assert d2['some_cookie'] == 'some_value' assert d3['some_cookie1'] == 'some_value1' def test_cookie_as_dict_keys(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.cookies.RequestsCookieJar() jar.set(key, value) jar.set(key1, value1) keys = jar.keys() assert keys == list(keys) # make sure one can use keys multiple times assert list(keys) == list(keys) def test_cookie_as_dict_values(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.cookies.RequestsCookieJar() jar.set(key, value) jar.set(key1, value1) values = jar.values() assert values == list(values) # make sure one can use values multiple times assert list(values) == list(values) def test_cookie_as_dict_items(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.cookies.RequestsCookieJar() jar.set(key, value) jar.set(key1, value1) items = jar.items() assert items == list(items) # make sure one can use items multiple times assert list(items) == list(items) def test_time_elapsed_blank(self, httpbin): r = requests.get(httpbin('get')) td = r.elapsed total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6) assert total_seconds > 0.0 def test_response_is_iterable(self): r = requests.Response() io = StringIO.StringIO('abc') read_ = io.read def read_mock(amt, decode_content=None): return read_(amt) setattr(io, 'read', read_mock) r.raw = io assert next(iter(r)) io.close() def test_response_decode_unicode(self): """ When called with decode_unicode, Response.iter_content should always return unicode. """ r = requests.Response() r._content_consumed = True r._content = b'the content' r.encoding = 'ascii' chunks = r.iter_content(decode_unicode=True) assert all(isinstance(chunk, str) for chunk in chunks) # also for streaming r = requests.Response() r.raw = io.BytesIO(b'the content') r.encoding = 'ascii' chunks = r.iter_content(decode_unicode=True) assert all(isinstance(chunk, str) for chunk in chunks) def test_request_and_response_are_pickleable(self, httpbin): r = requests.get(httpbin('get')) # verify we can pickle the original request assert pickle.loads(pickle.dumps(r.request)) # verify we can pickle the response and that we have access to # the original request. pr = pickle.loads(pickle.dumps(r)) assert r.request.url == pr.request.url assert r.request.headers == pr.request.headers def test_get_auth_from_url(self): url = 'http://user:pass@complex.url.com/path?query=yes' assert ('user', 'pass') == requests.utils.get_auth_from_url(url) def test_get_auth_from_url_encoded_spaces(self): url = 'http://user:pass%20pass@complex.url.com/path?query=yes' assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url) def test_get_auth_from_url_not_encoded_spaces(self): url = 'http://user:pass pass@complex.url.com/path?query=yes' assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url) def test_get_auth_from_url_percent_chars(self): url = 'http://user%25user:pass@complex.url.com/path?query=yes' assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url) def test_get_auth_from_url_encoded_hashes(self): url = 'http://user:pass%23pass@complex.url.com/path?query=yes' assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url) def test_cannot_send_unprepared_requests(self, httpbin): r = requests.Request(url=httpbin()) with pytest.raises(ValueError): requests.Session().send(r) def test_http_error(self): error = requests.exceptions.HTTPError() assert not error.response response = requests.Response() error = requests.exceptions.HTTPError(response=response) assert error.response == response error = requests.exceptions.HTTPError('message', response=response) assert str(error) == 'message' assert error.response == response def test_session_pickling(self, httpbin): r = requests.Request('GET', httpbin('get')) s = requests.Session() s = pickle.loads(pickle.dumps(s)) s.proxies = getproxies() r = s.send(r.prepare()) assert r.status_code == 200 def test_fixes_1329(self, httpbin): """ Ensure that header updates are done case-insensitively. """ s = requests.Session() s.headers.update({'ACCEPT': 'BOGUS'}) s.headers.update({'accept': 'application/json'}) r = s.get(httpbin('get')) headers = r.request.headers assert headers['accept'] == 'application/json' assert headers['Accept'] == 'application/json' assert headers['ACCEPT'] == 'application/json' def test_uppercase_scheme_redirect(self, httpbin): parts = urlparse(httpbin('html')) url = "HTTP://" + parts.netloc + parts.path r = requests.get(httpbin('redirect-to'), params={'url': url}) assert r.status_code == 200 assert r.url.lower() == url.lower() def test_transport_adapter_ordering(self): s = requests.Session() order = ['https://', 'http://'] assert order == list(s.adapters) s.mount('http://git', HTTPAdapter()) s.mount('http://github', HTTPAdapter()) s.mount('http://github.com', HTTPAdapter()) s.mount('http://github.com/about/', HTTPAdapter()) order = [ 'http://github.com/about/', 'http://github.com', 'http://github', 'http://git', 'https://', 'http://', ] assert order == list(s.adapters) s.mount('http://gittip', HTTPAdapter()) s.mount('http://gittip.com', HTTPAdapter()) s.mount('http://gittip.com/about/', HTTPAdapter()) order = [ 'http://github.com/about/', 'http://gittip.com/about/', 'http://github.com', 'http://gittip.com', 'http://github', 'http://gittip', 'http://git', 'https://', 'http://', ] assert order == list(s.adapters) s2 = requests.Session() s2.adapters = {'http://': HTTPAdapter()} s2.mount('https://', HTTPAdapter()) assert 'http://' in s2.adapters assert 'https://' in s2.adapters def test_header_remove_is_case_insensitive(self, httpbin): # From issue #1321 s = requests.Session() s.headers['foo'] = 'bar' r = s.get(httpbin('get'), headers={'FOO': None}) assert 'foo' not in r.request.headers def test_params_are_merged_case_sensitive(self, httpbin): s = requests.Session() s.params['foo'] = 'bar' r = s.get(httpbin('get'), params={'FOO': 'bar'}) assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'} def test_long_authinfo_in_url(self): url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format( 'E8A3BE87-9E3F-4620-8858-95478E385B5B', 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E', 'exactly-------------sixty-----------three------------characters', ) r = requests.Request('GET', url).prepare() assert r.url == url def test_header_keys_are_native(self, httpbin): headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'} r = requests.Request('GET', httpbin('get'), headers=headers) p = r.prepare() # This is testing that they are builtin strings. A bit weird, but there # we go. assert 'unicode' in p.headers.keys() assert 'byte' in p.headers.keys() def test_can_send_nonstring_objects_with_files(self, httpbin): data = {'a': 0.0} files = {'b': 'foo'} r = requests.Request('POST', httpbin('post'), data=data, files=files) p = r.prepare() assert 'multipart/form-data' in p.headers['Content-Type'] def test_can_send_bytes_bytearray_objects_with_files(self, httpbin): # Test bytes: data = {'a': 'this is a string'} files = {'b': b'foo'} r = requests.Request('POST', httpbin('post'), data=data, files=files) p = r.prepare() assert 'multipart/form-data' in p.headers['Content-Type'] # Test bytearrays: files = {'b': bytearray(b'foo')} r = requests.Request('POST', httpbin('post'), data=data, files=files) p = r.prepare() assert 'multipart/form-data' in p.headers['Content-Type'] def test_can_send_file_object_with_non_string_filename(self, httpbin): f = io.BytesIO() f.name = 2 r = requests.Request('POST', httpbin('post'), files={'f': f}) p = r.prepare() assert 'multipart/form-data' in p.headers['Content-Type'] def test_autoset_header_values_are_native(self, httpbin): data = 'this is a string' length = '16' req = requests.Request('POST', httpbin('post'), data=data) p = req.prepare() assert p.headers['Content-Length'] == length def test_nonhttp_schemes_dont_check_URLs(self): test_urls = ( 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==', 'file:///etc/passwd', 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431', ) for test_url in test_urls: req = requests.Request('GET', test_url) preq = req.prepare() assert test_url == preq.url def test_auth_is_stripped_on_redirect_off_host(self, httpbin): r = requests.get( httpbin('redirect-to'), params={'url': 'http://www.google.co.uk'}, auth=('user', 'pass'), ) assert r.history[0].request.headers['Authorization'] assert not r.request.headers.get('Authorization', '') def test_auth_is_retained_for_redirect_on_host(self, httpbin): r = requests.get(httpbin('redirect/1'), auth=('user', 'pass')) h1 = r.history[0].request.headers['Authorization'] h2 = r.request.headers['Authorization'] assert h1 == h2 def test_manual_redirect_with_partial_body_read(self, httpbin): s = requests.Session() r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True) assert r1.is_redirect rg = s.resolve_redirects(r1, r1.request, stream=True) # read only the first eight bytes of the response body, # then follow the redirect r1.iter_content(8) r2 = next(rg) assert r2.is_redirect # read all of the response via iter_content, # then follow the redirect for _ in r2.iter_content(): pass r3 = next(rg) assert not r3.is_redirect def _patch_adapter_gzipped_redirect(self, session, url): adapter = session.get_adapter(url=url) org_build_response = adapter.build_response self._patched_response = False def build_response(*args, **kwargs): resp = org_build_response(*args, **kwargs) if not self._patched_response: resp.raw.headers['content-encoding'] = 'gzip' self._patched_response = True return resp adapter.build_response = build_response def test_redirect_with_wrong_gzipped_header(self, httpbin): s = requests.Session() url = httpbin('redirect/1') self._patch_adapter_gzipped_redirect(s, url) s.get(url) def test_basic_auth_str_is_always_native(self): s = _basic_auth_str("test", "test") assert isinstance(s, builtin_str) assert s == "Basic dGVzdDp0ZXN0" def test_requests_history_is_saved(self, httpbin): r = requests.get(httpbin('redirect/5')) total = r.history[-1].history i = 0 for item in r.history: assert item.history == total[0:i] i = i + 1 def test_json_param_post_content_type_works(self, httpbin): r = requests.post( httpbin('post'), json={'life': 42} ) assert r.status_code == 200 assert 'application/json' in r.request.headers['Content-Type'] assert {'life': 42} == r.json()['json'] def test_json_param_post_should_not_override_data_param(self, httpbin): r = requests.Request(method='POST', url=httpbin('post'), data={'stuff': 'elixr'}, json={'music': 'flute'}) prep = r.prepare() assert 'stuff=elixr' == prep.body def test_response_iter_lines(self, httpbin): r = requests.get(httpbin('stream/4'), stream=True) assert r.status_code == 200 it = r.iter_lines() next(it) assert len(list(it)) == 3 def test_unconsumed_session_response_closes_connection(self, httpbin): s = requests.session() with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response: pass assert response._content_consumed is False assert response.raw.closed @pytest.mark.xfail def test_response_iter_lines_reentrant(self, httpbin): """Response.iter_lines() is not reentrant safe""" r = requests.get(httpbin('stream/4'), stream=True) assert r.status_code == 200 next(r.iter_lines()) assert len(list(r.iter_lines())) == 3 class TestContentEncodingDetection(unittest.TestCase): def test_none(self): encodings = requests.utils.get_encodings_from_content('') assert not len(encodings) def test_html_charset(self): """HTML5 meta charset attribute""" content = '<meta charset="UTF-8">' encodings = requests.utils.get_encodings_from_content(content) assert len(encodings) == 1 assert encodings[0] == 'UTF-8' def test_html4_pragma(self): """HTML4 pragma directive""" content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">' encodings = requests.utils.get_encodings_from_content(content) assert len(encodings) == 1 assert encodings[0] == 'UTF-8' def test_xhtml_pragma(self): """XHTML 1.x served with text/html MIME type""" content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />' encodings = requests.utils.get_encodings_from_content(content) assert len(encodings) == 1 assert encodings[0] == 'UTF-8' def test_xml(self): """XHTML 1.x served as XML""" content = '<?xml version="1.0" encoding="UTF-8"?>' encodings = requests.utils.get_encodings_from_content(content) assert len(encodings) == 1 assert encodings[0] == 'UTF-8' def test_precedence(self): content = ''' <?xml version="1.0" encoding="XML"?> <meta charset="HTML5"> <meta http-equiv="Content-type" content="text/html;charset=HTML4" /> '''.strip() encodings = requests.utils.get_encodings_from_content(content) assert encodings == ['HTML5', 'HTML4', 'XML'] class TestCaseInsensitiveDict(unittest.TestCase): def test_mapping_init(self): cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}) assert len(cid) == 2 assert 'foo' in cid assert 'bar' in cid def test_iterable_init(self): cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]) assert len(cid) == 2 assert 'foo' in cid assert 'bar' in cid def test_kwargs_init(self): cid = CaseInsensitiveDict(FOO='foo', BAr='bar') assert len(cid) == 2 assert 'foo' in cid assert 'bar' in cid def test_docstring_example(self): cid = CaseInsensitiveDict() cid['Accept'] = 'application/json' assert cid['aCCEPT'] == 'application/json' assert list(cid) == ['Accept'] def test_len(self): cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'}) cid['A'] = 'a' assert len(cid) == 2 def test_getitem(self): cid = CaseInsensitiveDict({'Spam': 'blueval'}) assert cid['spam'] == 'blueval' assert cid['SPAM'] == 'blueval' def test_fixes_649(self): """__setitem__ should behave case-insensitively.""" cid = CaseInsensitiveDict() cid['spam'] = 'oneval' cid['Spam'] = 'twoval' cid['sPAM'] = 'redval' cid['SPAM'] = 'blueval' assert cid['spam'] == 'blueval' assert cid['SPAM'] == 'blueval' assert list(cid.keys()) == ['SPAM'] def test_delitem(self): cid = CaseInsensitiveDict() cid['Spam'] = 'someval' del cid['sPam'] assert 'spam' not in cid assert len(cid) == 0 def test_contains(self): cid = CaseInsensitiveDict() cid['Spam'] = 'someval' assert 'Spam' in cid assert 'spam' in cid assert 'SPAM' in cid assert 'sPam' in cid assert 'notspam' not in cid def test_get(self): cid = CaseInsensitiveDict() cid['spam'] = 'oneval' cid['SPAM'] = 'blueval' assert cid.get('spam') == 'blueval' assert cid.get('SPAM') == 'blueval' assert cid.get('sPam') == 'blueval' assert cid.get('notspam', 'default') == 'default' def test_update(self): cid = CaseInsensitiveDict() cid['spam'] = 'blueval' cid.update({'sPam': 'notblueval'}) assert cid['spam'] == 'notblueval' cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}) cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'}) assert len(cid) == 2 assert cid['foo'] == 'anotherfoo' assert cid['bar'] == 'anotherbar' def test_update_retains_unchanged(self): cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'}) cid.update({'foo': 'newfoo'}) assert cid['bar'] == 'bar' def test_iter(self): cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'}) keys = frozenset(['Spam', 'Eggs']) assert frozenset(iter(cid)) == keys def test_equality(self): cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'}) othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'}) assert cid == othercid del othercid['spam'] assert cid != othercid assert cid == {'spam': 'blueval', 'eggs': 'redval'} assert cid != object() def test_setdefault(self): cid = CaseInsensitiveDict({'Spam': 'blueval'}) assert cid.setdefault('spam', 'notblueval') == 'blueval' assert cid.setdefault('notspam', 'notblueval') == 'notblueval' def test_lower_items(self): cid = CaseInsensitiveDict({ 'Accept': 'application/json', 'user-Agent': 'requests', }) keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items()) lowerkeyset = frozenset(['accept', 'user-agent']) assert keyset == lowerkeyset def test_preserve_key_case(self): cid = CaseInsensitiveDict({ 'Accept': 'application/json', 'user-Agent': 'requests', }) keyset = frozenset(['Accept', 'user-Agent']) assert frozenset(i[0] for i in cid.items()) == keyset assert frozenset(cid.keys()) == keyset assert frozenset(cid) == keyset def test_preserve_last_key_case(self): cid = CaseInsensitiveDict({ 'Accept': 'application/json', 'user-Agent': 'requests', }) cid.update({'ACCEPT': 'application/json'}) cid['USER-AGENT'] = 'requests' keyset = frozenset(['ACCEPT', 'USER-AGENT']) assert frozenset(i[0] for i in cid.items()) == keyset assert frozenset(cid.keys()) == keyset assert frozenset(cid) == keyset def test_copy(self): cid = CaseInsensitiveDict({ 'Accept': 'application/json', 'user-Agent': 'requests', }) cid_copy = cid.copy() assert cid == cid_copy cid['changed'] = True assert cid != cid_copy class UtilsTestCase(unittest.TestCase): def test_super_len_io_streams(self): """ Ensures that we properly deal with different kinds of IO streams. """ # uses StringIO or io.StringIO (see import above) from io import BytesIO from requests.utils import super_len assert super_len(StringIO.StringIO()) == 0 assert super_len( StringIO.StringIO('with so much drama in the LBC')) == 29 assert super_len(BytesIO()) == 0 assert super_len( BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40 try: import cStringIO except ImportError: pass else: assert super_len( cStringIO.StringIO('but some how, some way...')) == 25 def test_super_len_correctly_calculates_len_of_partially_read_file(self): """Ensure that we handle partially consumed file like objects.""" from requests.utils import super_len s = StringIO.StringIO() s.write('foobarbogus') assert super_len(s) == 0 def test_get_environ_proxies_ip_ranges(self): """Ensures that IP addresses are correctly matches with ranges in no_proxy variable.""" from requests.utils import get_environ_proxies os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1" assert get_environ_proxies('http://192.168.0.1:5000/') == {} assert get_environ_proxies('http://192.168.0.1/') == {} assert get_environ_proxies('http://172.16.1.1/') == {} assert get_environ_proxies('http://172.16.1.1:5000/') == {} assert get_environ_proxies('http://192.168.1.1:5000/') != {} assert get_environ_proxies('http://192.168.1.1/') != {} def test_get_environ_proxies(self): """Ensures that IP addresses are correctly matches with ranges in no_proxy variable.""" from requests.utils import get_environ_proxies os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1" assert get_environ_proxies( 'http://localhost.localdomain:5000/v1.0/') == {} assert get_environ_proxies('http://www.requests.com/') != {} def test_select_proxies(self): """Make sure we can select per-host proxies correctly.""" from requests.utils import select_proxy proxies = {'http': 'http://http.proxy', 'http://some.host': 'http://some.host.proxy'} assert select_proxy('hTTp://u:p@Some.Host/path', proxies) == 'http://some.host.proxy' assert select_proxy('hTTp://u:p@Other.Host/path', proxies) == 'http://http.proxy' assert select_proxy('hTTps://Other.Host', proxies) is None def test_guess_filename_when_int(self): from requests.utils import guess_filename assert None is guess_filename(1) def test_guess_filename_when_filename_is_an_int(self): from requests.utils import guess_filename fake = type('Fake', (object,), {'name': 1})() assert None is guess_filename(fake) def test_guess_filename_with_file_like_obj(self): from requests.utils import guess_filename from requests import compat fake = type('Fake', (object,), {'name': b'value'})() guessed_name = guess_filename(fake) assert b'value' == guessed_name assert isinstance(guessed_name, compat.bytes) def test_guess_filename_with_unicode_name(self): from requests.utils import guess_filename from requests import compat filename = b'value'.decode('utf-8') fake = type('Fake', (object,), {'name': filename})() guessed_name = guess_filename(fake) assert filename == guessed_name assert isinstance(guessed_name, compat.str) def test_is_ipv4_address(self): from requests.utils import is_ipv4_address assert is_ipv4_address('8.8.8.8') assert not is_ipv4_address('8.8.8.8.8') assert not is_ipv4_address('localhost.localdomain') def test_is_valid_cidr(self): from requests.utils import is_valid_cidr assert not is_valid_cidr('8.8.8.8') assert is_valid_cidr('192.168.1.0/24') def test_dotted_netmask(self): from requests.utils import dotted_netmask assert dotted_netmask(8) == '255.0.0.0' assert dotted_netmask(24) == '255.255.255.0' assert dotted_netmask(25) == '255.255.255.128' def test_address_in_network(self): from requests.utils import address_in_network assert address_in_network('192.168.1.1', '192.168.1.0/24') assert not address_in_network('172.16.0.1', '192.168.1.0/24') def test_get_auth_from_url(self): """Ensures that username and password in well-encoded URI as per RFC 3986 are correclty extracted.""" from requests.utils import get_auth_from_url from requests.compat import quote percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] " url_address = "request.com/url.html#test" url = "http://" + quote( percent_encoding_test_chars, '') + ':' + quote( percent_encoding_test_chars, '') + '@' + url_address (username, password) = get_auth_from_url(url) assert username == percent_encoding_test_chars assert password == percent_encoding_test_chars def test_requote_uri_with_unquoted_percents(self): """Ensure we handle unquoted percent signs in redirects. See: https://github.com/kennethreitz/requests/issues/2356 """ from requests.utils import requote_uri bad_uri = 'http://example.com/fiz?buz=%ppicture' quoted = 'http://example.com/fiz?buz=%25ppicture' assert quoted == requote_uri(bad_uri) def test_requote_uri_properly_requotes(self): """Ensure requoting doesn't break expectations.""" from requests.utils import requote_uri quoted = 'http://example.com/fiz?buz=%25ppicture' assert quoted == requote_uri(quoted) class TestMorselToCookieExpires(unittest.TestCase): """Tests for morsel_to_cookie when morsel contains expires.""" def test_expires_valid_str(self): """Test case where we convert expires from string time.""" morsel = Morsel() morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT' cookie = morsel_to_cookie(morsel) assert cookie.expires == 1 def test_expires_invalid_int(self): """Test case where an invalid type is passed for expires.""" morsel = Morsel() morsel['expires'] = 100 with pytest.raises(TypeError): morsel_to_cookie(morsel) def test_expires_invalid_str(self): """Test case where an invalid string is input.""" morsel = Morsel() morsel['expires'] = 'woops' with pytest.raises(ValueError): morsel_to_cookie(morsel) def test_expires_none(self): """Test case where expires is None.""" morsel = Morsel() morsel['expires'] = None cookie = morsel_to_cookie(morsel) assert cookie.expires is None class TestMorselToCookieMaxAge(unittest.TestCase): """Tests for morsel_to_cookie when morsel contains max-age.""" def test_max_age_valid_int(self): """Test case where a valid max age in seconds is passed.""" morsel = Morsel() morsel['max-age'] = 60 cookie = morsel_to_cookie(morsel) assert isinstance(cookie.expires, int) def test_max_age_invalid_str(self): """Test case where a invalid max age is passed.""" morsel = Morsel() morsel['max-age'] = 'woops' with pytest.raises(TypeError): morsel_to_cookie(morsel) class TestTimeout: def test_stream_timeout(self, httpbin): try: requests.get(httpbin('delay/10'), timeout=2.0) except requests.exceptions.Timeout as e: assert 'Read timed out' in e.args[0].args[0] def test_invalid_timeout(self, httpbin): with pytest.raises(ValueError) as e: requests.get(httpbin('get'), timeout=(3, 4, 5)) assert '(connect, read)' in str(e) with pytest.raises(ValueError) as e: requests.get(httpbin('get'), timeout="foo") assert 'must be an int or float' in str(e) def test_none_timeout(self, httpbin): """ Check that you can set None as a valid timeout value. To actually test this behavior, we'd want to check that setting the timeout to None actually lets the request block past the system default timeout. However, this would make the test suite unbearably slow. Instead we verify that setting the timeout to None does not prevent the request from succeeding. """ r = requests.get(httpbin('get'), timeout=None) assert r.status_code == 200 def test_read_timeout(self, httpbin): try: requests.get(httpbin('delay/10'), timeout=(None, 0.1)) assert False, "The recv() request should time out." except ReadTimeout: pass def test_connect_timeout(self): try: requests.get(TARPIT, timeout=(0.1, None)) assert False, "The connect() request should time out." except ConnectTimeout as e: assert isinstance(e, ConnectionError) assert isinstance(e, Timeout) def test_total_timeout_connect(self): try: requests.get(TARPIT, timeout=(0.1, 0.1)) assert False, "The connect() request should time out." except ConnectTimeout: pass def test_encoded_methods(self, httpbin): """See: https://github.com/kennethreitz/requests/issues/2316""" r = requests.request(b'GET', httpbin('get')) assert r.ok SendCall = collections.namedtuple('SendCall', ('args', 'kwargs')) class RedirectSession(SessionRedirectMixin): def __init__(self, order_of_redirects): self.redirects = order_of_redirects self.calls = [] self.max_redirects = 30 self.cookies = {} self.trust_env = False def send(self, *args, **kwargs): self.calls.append(SendCall(args, kwargs)) return self.build_response() def build_response(self): request = self.calls[-1].args[0] r = requests.Response() try: r.status_code = int(self.redirects.pop(0)) except IndexError: r.status_code = 200 r.headers = CaseInsensitiveDict({'Location': '/'}) r.raw = self._build_raw() r.request = request return r def _build_raw(self): string = StringIO.StringIO('') setattr(string, 'release_conn', lambda *args: args) return string class TestRedirects: default_keyword_args = { 'stream': False, 'verify': True, 'cert': None, 'timeout': None, 'allow_redirects': False, 'proxies': {}, } def test_requests_are_updated_each_time(self, httpbin): session = RedirectSession([303, 307]) prep = requests.Request('POST', httpbin('post')).prepare() r0 = session.send(prep) assert r0.request.method == 'POST' assert session.calls[-1] == SendCall((r0.request,), {}) redirect_generator = session.resolve_redirects(r0, prep) for response in redirect_generator: assert response.request.method == 'GET' send_call = SendCall((response.request,), TestRedirects.default_keyword_args) assert session.calls[-1] == send_call @pytest.fixture def list_of_tuples(): return [ (('a', 'b'), ('c', 'd')), (('c', 'd'), ('a', 'b')), (('a', 'b'), ('c', 'd'), ('e', 'f')), ] def test_data_argument_accepts_tuples(list_of_tuples): """ Ensure that the data argument will accept tuples of strings and properly encode them. """ for data in list_of_tuples: p = PreparedRequest() p.prepare( method='GET', url='http://www.example.com', data=data, hooks=default_hooks() ) assert p.body == urlencode(data) def assert_copy(p, p_copy): for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'): assert getattr(p, attr) == getattr(p_copy, attr) def test_prepared_request_empty_copy(): p = PreparedRequest() assert_copy(p, p.copy()) def test_prepared_request_no_cookies_copy(): p = PreparedRequest() p.prepare( method='GET', url='http://www.example.com', data='foo=bar', hooks=default_hooks() ) assert_copy(p, p.copy()) def test_prepared_request_complete_copy(): p = PreparedRequest() p.prepare( method='GET', url='http://www.example.com', data='foo=bar', hooks=default_hooks(), cookies={'foo': 'bar'} ) assert_copy(p, p.copy()) def test_prepare_unicode_url(): p = PreparedRequest() p.prepare( method='GET', url=u('http://www.example.com/üniçø∂é'), ) assert_copy(p, p.copy()) def test_urllib3_retries(httpbin): from requests.packages.urllib3.util import Retry s = requests.Session() s.mount('http://', HTTPAdapter(max_retries=Retry( total=2, status_forcelist=[500] ))) with pytest.raises(RetryError): s.get(httpbin('status/500')) def test_urllib3_pool_connection_closed(httpbin): s = requests.Session() s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0)) try: s.get(httpbin('status/200')) except ConnectionError as e: assert u"Pool is closed." in str(e) def test_vendor_aliases(): from requests.packages import urllib3 from requests.packages import chardet with pytest.raises(ImportError): from requests.packages import webbrowser if __name__ == '__main__': unittest.main()
mbareta/edx-platform-ft
refs/heads/open-release/eucalyptus.master
common/lib/xmodule/xmodule/modulestore/tests/factories.py
24
""" Factories for use in tests of XBlocks. """ import datetime import functools import pymongo.message import pytz import threading import traceback from collections import defaultdict from contextlib import contextmanager from uuid import uuid4 from factory import Factory, Sequence, lazy_attribute_sequence, lazy_attribute from factory.containers import CyclicDefinitionError from mock import patch from nose.tools import assert_less_equal, assert_greater_equal import dogstats_wrapper as dog_stats_api from opaque_keys.edx.locations import Location from opaque_keys.edx.keys import UsageKey from xblock.core import XBlock from xmodule.modulestore import prefer_xmodules, ModuleStoreEnum from xmodule.modulestore.tests.sample_courses import default_block_info_tree, TOY_BLOCK_INFO_TREE from xmodule.tabs import CourseTab from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT from xmodule.course_module import Textbook class Dummy(object): pass class XModuleFactoryLock(threading.local): """ This class exists to store whether XModuleFactory can be accessed in a safe way (meaning, in a context where the data it creates will be cleaned up). Users of XModuleFactory (or its subclasses) should only call XModuleFactoryLock.enable after ensuring that a) the modulestore will be cleaned up, and b) that XModuleFactoryLock.disable will be called. """ def __init__(self): super(XModuleFactoryLock, self).__init__() self._enabled = False def enable(self): """ Enable XModuleFactories. This should only be turned in a context where the modulestore will be reset at the end of the test (such as inside ModuleStoreTestCase). """ self._enabled = True def disable(self): """ Disable XModuleFactories. This should be called once the data from the factory has been cleaned up. """ self._enabled = False def is_enabled(self): """ Return whether XModuleFactories are enabled. """ return self._enabled XMODULE_FACTORY_LOCK = XModuleFactoryLock() class XModuleFactory(Factory): """ Factory for XModules """ # We have to give a model for Factory. # However, the class that we create is actually determined by the category # specified in the factory class Meta(object): model = Dummy @lazy_attribute def modulestore(self): msg = "XMODULE_FACTORY_LOCK not enabled. Please use ModuleStoreTestCase as your test baseclass." assert XMODULE_FACTORY_LOCK.is_enabled(), msg from xmodule.modulestore.django import modulestore return modulestore() last_course = threading.local() class CourseFactory(XModuleFactory): """ Factory for XModule courses. """ org = Sequence('org.{}'.format) number = Sequence('course_{}'.format) display_name = Sequence('Run {}'.format) # pylint: disable=unused-argument @classmethod def _create(cls, target_class, **kwargs): """ Create and return a new course. For performance reasons, we do not emit signals during this process, but if you need signals to run, you can pass `emit_signals=True` to this method. """ # All class attributes (from this class and base classes) are # passed in via **kwargs. However, some of those aren't actual field values, # so pop those off for use separately org = kwargs.pop('org', None) # because the factory provides a default 'number' arg, prefer the non-defaulted 'course' arg if any number = kwargs.pop('course', kwargs.pop('number', None)) store = kwargs.pop('modulestore') name = kwargs.get('name', kwargs.get('run', Location.clean(kwargs.get('display_name')))) run = kwargs.pop('run', name) user_id = kwargs.pop('user_id', ModuleStoreEnum.UserID.test) emit_signals = kwargs.pop('emit_signals', False) # Pass the metadata just as field=value pairs kwargs.update(kwargs.pop('metadata', {})) default_store_override = kwargs.pop('default_store', None) with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred): course_key = store.make_course_key(org, number, run) with store.bulk_operations(course_key, emit_signals=emit_signals): if default_store_override is not None: with store.default_store(default_store_override): new_course = store.create_course(org, number, run, user_id, fields=kwargs) else: new_course = store.create_course(org, number, run, user_id, fields=kwargs) last_course.loc = new_course.location return new_course class SampleCourseFactory(CourseFactory): """ Factory for sample courses using block_info_tree definitions. """ @classmethod def _create(cls, target_class, **kwargs): """ Create and return a new sample course. See CourseFactory for customization kwargs. """ block_info_tree = kwargs.pop('block_info_tree', default_block_info_tree) store = kwargs.get('modulestore') user_id = kwargs.get('user_id', ModuleStoreEnum.UserID.test) with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, None): course = super(SampleCourseFactory, cls)._create(target_class, **kwargs) def create_sub_tree(parent_loc, block_info): """Recursively creates a sub_tree on this parent_loc with this block.""" block = store.create_child( user_id, parent_loc, block_info.category, block_id=block_info.block_id, fields=block_info.fields, ) for tree in block_info.sub_tree: create_sub_tree(block.location, tree) for tree in block_info_tree: create_sub_tree(course.location, tree) store.publish(course.location, user_id) return course class ToyCourseFactory(SampleCourseFactory): """ Factory for sample course that is equivalent to the toy xml course. """ org = 'edX' course = 'toy' run = '2012_Fall' display_name = 'Toy Course' @classmethod def _create(cls, target_class, **kwargs): """ Create and return a new toy course instance. See SampleCourseFactory for customization kwargs. """ store = kwargs.get('modulestore') user_id = kwargs.get('user_id', ModuleStoreEnum.UserID.test) fields = { 'block_info_tree': TOY_BLOCK_INFO_TREE, 'textbooks': [Textbook("Textbook", "path/to/a/text_book")], 'wiki_slug': "toy", 'graded': True, 'discussion_topics': {"General": {"id": "i4x-edX-toy-course-2012_Fall"}}, 'graceperiod': datetime.timedelta(days=2, seconds=21599), 'start': datetime.datetime(2015, 07, 17, 12, tzinfo=pytz.utc), 'xml_attributes': {"filename": ["course/2012_Fall.xml", "course/2012_Fall.xml"]}, 'pdf_textbooks': [ { "tab_title": "Sample Multi Chapter Textbook", "id": "MyTextbook", "chapters": [ {"url": "/static/Chapter1.pdf", "title": "Chapter 1"}, {"url": "/static/Chapter2.pdf", "title": "Chapter 2"} ] } ], 'course_image': "just_a_test.jpg", } fields.update(kwargs) toy_course = super(ToyCourseFactory, cls)._create( target_class, **fields ) with store.bulk_operations(toy_course.id, emit_signals=False): with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, toy_course.id): store.create_item( user_id, toy_course.id, "about", block_id="short_description", fields={"data": "A course about toys."} ) store.create_item( user_id, toy_course.id, "about", block_id="effort", fields={"data": "6 hours"} ) store.create_item( user_id, toy_course.id, "about", block_id="end_date", fields={"data": "TBD"} ) store.create_item( user_id, toy_course.id, "course_info", "handouts", fields={"data": "<a href='/static/handouts/sample_handout.txt'>Sample</a>"} ) store.create_item( user_id, toy_course.id, "static_tab", "resources", fields={"display_name": "Resources"}, ) store.create_item( user_id, toy_course.id, "static_tab", "syllabus", fields={"display_name": "Syllabus"}, ) return toy_course class LibraryFactory(XModuleFactory): """ Factory for creating a content library """ org = Sequence('org{}'.format) library = Sequence('lib{}'.format) display_name = Sequence('Test Library {}'.format) # pylint: disable=unused-argument @classmethod def _create(cls, target_class, **kwargs): """ Create a library with a unique name and key. All class attributes (from this class and base classes) are automagically passed in via **kwargs. """ # some of the kwargst actual field values, so pop those off for use separately: org = kwargs.pop('org') library = kwargs.pop('library') store = kwargs.pop('modulestore') user_id = kwargs.pop('user_id', ModuleStoreEnum.UserID.test) # Pass the metadata just as field=value pairs kwargs.update(kwargs.pop('metadata', {})) default_store_override = kwargs.pop('default_store', ModuleStoreEnum.Type.split) with store.default_store(default_store_override): new_library = store.create_library(org, library, user_id, fields=kwargs) return new_library class ItemFactory(XModuleFactory): """ Factory for XModule items. """ category = 'chapter' parent = None @lazy_attribute_sequence def display_name(self, n): return "{} {}".format(self.category, n) @lazy_attribute def location(self): if self.display_name is None: dest_name = uuid4().hex else: dest_name = self.display_name.replace(" ", "_") new_location = self.parent_location.course_key.make_usage_key( self.category, dest_name ) return new_location @lazy_attribute def parent_location(self): default_location = getattr(last_course, 'loc', None) try: parent = self.parent # This error is raised if the caller hasn't provided either parent or parent_location # In this case, we'll just return the default parent_location except CyclicDefinitionError: return default_location if parent is None: return default_location return parent.location @classmethod def _create(cls, target_class, **kwargs): """ Uses ``**kwargs``: :parent_location: (required): the location of the parent module (e.g. the parent course or section) :category: the category of the resulting item. :data: (optional): the data for the item (e.g. XML problem definition for a problem item) :display_name: (optional): the display name of the item :metadata: (optional): dictionary of metadata attributes :boilerplate: (optional) the boilerplate for overriding field values :publish_item: (optional) whether or not to publish the item (default is True) :target_class: is ignored """ # All class attributes (from this class and base classes) are # passed in via **kwargs. However, some of those aren't actual field values, # so pop those off for use separately # catch any old style users before they get into trouble assert 'template' not in kwargs parent_location = kwargs.pop('parent_location', None) data = kwargs.pop('data', None) category = kwargs.pop('category', None) display_name = kwargs.pop('display_name', None) metadata = kwargs.pop('metadata', {}) location = kwargs.pop('location') user_id = kwargs.pop('user_id', ModuleStoreEnum.UserID.test) publish_item = kwargs.pop('publish_item', True) assert isinstance(location, UsageKey) assert location != parent_location store = kwargs.pop('modulestore') # This code was based off that in cms/djangoapps/contentstore/views.py parent = kwargs.pop('parent', None) or store.get_item(parent_location) with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred): if 'boilerplate' in kwargs: template_id = kwargs.pop('boilerplate') clz = XBlock.load_class(category, select=prefer_xmodules) template = clz.get_template(template_id) assert template is not None metadata.update(template.get('metadata', {})) if not isinstance(data, basestring): data.update(template.get('data')) # replace the display name with an optional parameter passed in from the caller if display_name is not None: metadata['display_name'] = display_name module = store.create_child( user_id, parent.location, location.block_type, block_id=location.block_id, metadata=metadata, definition_data=data, runtime=parent.runtime, fields=kwargs, ) # VS[compat] cdodge: This is a hack because static_tabs also have references from the course module, so # if we add one then we need to also add it to the policy information (i.e. metadata) # we should remove this once we can break this reference from the course to static tabs if category == 'static_tab': dog_stats_api.increment( DEPRECATION_VSCOMPAT_EVENT, tags=( "location:itemfactory_create_static_tab", u"block:{}".format(location.block_type), ) ) course = store.get_course(location.course_key) course.tabs.append( CourseTab.load('static_tab', name='Static Tab', url_slug=location.name) ) store.update_item(course, user_id) # parent and publish the item, so it can be accessed if 'detached' not in module._class_tags: parent.children.append(location) store.update_item(parent, user_id) if publish_item: published_parent = store.publish(parent.location, user_id) # module is last child of parent return published_parent.get_children()[-1] else: return store.get_item(location) elif publish_item: return store.publish(location, user_id) else: return module @contextmanager def check_exact_number_of_calls(object_with_method, method_name, num_calls): """ Instruments the given method on the given object to verify the number of calls to the method is exactly equal to 'num_calls'. """ with check_number_of_calls(object_with_method, method_name, num_calls, num_calls): yield def check_number_of_calls(object_with_method, method_name, maximum_calls, minimum_calls=1): """ Instruments the given method on the given object to verify the number of calls to the method is less than or equal to the expected maximum_calls and greater than or equal to the expected minimum_calls. """ return check_sum_of_calls(object_with_method, [method_name], maximum_calls, minimum_calls) class StackTraceCounter(object): """ A class that counts unique stack traces underneath a particular stack frame. """ def __init__(self, stack_depth, include_arguments=True): """ Arguments: stack_depth (int): The number of stack frames above this constructor to capture. include_arguments (bool): Whether to store the arguments that are passed when capturing a stack trace. """ self.include_arguments = include_arguments self._top_of_stack = traceback.extract_stack(limit=stack_depth)[0] if self.include_arguments: self._stacks = defaultdict(lambda: defaultdict(int)) else: self._stacks = defaultdict(int) def capture_stack(self, args, kwargs): """ Record the stack frames starting at the caller of this method, and ending at the top of the stack as defined by the ``stack_depth``. Arguments: args: The positional arguments to capture at this stack frame kwargs: The keyword arguments to capture at this stack frame """ # pylint: disable=broad-except stack = traceback.extract_stack()[:-2] if self._top_of_stack in stack: stack = stack[stack.index(self._top_of_stack):] if self.include_arguments: safe_args = [] for arg in args: try: safe_args.append(repr(arg)) except Exception as exc: safe_args.append('<un-repr-able value: {}'.format(exc)) safe_kwargs = {} for key, kwarg in kwargs.items(): try: safe_kwargs[key] = repr(kwarg) except Exception as exc: safe_kwargs[key] = '<un-repr-able value: {}'.format(exc) self._stacks[tuple(stack)][tuple(safe_args), tuple(safe_kwargs.items())] += 1 else: self._stacks[tuple(stack)] += 1 @property def total_calls(self): """ Return the total number of stacks recorded. """ return sum(self.stack_calls(stack) for stack in self._stacks) def stack_calls(self, stack): """ Return the number of calls to the supplied ``stack``. """ if self.include_arguments: return sum(self._stacks[stack].values()) else: return self._stacks[stack] def __iter__(self): """ Iterate over all unique captured stacks. """ return iter(sorted(self._stacks.keys(), key=lambda stack: (self.stack_calls(stack), stack), reverse=True)) def __getitem__(self, stack): """ Return the set of captured calls with the supplied stack. """ return self._stacks[stack] @classmethod def capture_call(cls, func, stack_depth, include_arguments=True): """ A decorator that wraps ``func``, and captures each call to ``func``, recording the stack trace, and optionally the arguments that the function is called with. Arguments: func: the function to wrap stack_depth: how far up the stack to truncate the stored stack traces ( this is counted from the call to ``capture_call``, rather than calls to the captured function). """ stacks = StackTraceCounter(stack_depth, include_arguments) # pylint: disable=missing-docstring @functools.wraps(func) def capture(*args, **kwargs): stacks.capture_stack(args, kwargs) return func(*args, **kwargs) capture.stack_counter = stacks return capture @contextmanager def check_sum_of_calls(object_, methods, maximum_calls, minimum_calls=1, include_arguments=True): """ Instruments the given methods on the given object to verify that the total sum of calls made to the methods falls between minumum_calls and maximum_calls. """ mocks = { method: StackTraceCounter.capture_call( getattr(object_, method), stack_depth=7, include_arguments=include_arguments ) for method in methods } with patch.multiple(object_, **mocks): yield call_count = sum(capture_fn.stack_counter.total_calls for capture_fn in mocks.values()) # Assertion errors don't handle multi-line values, so pretty-print to std-out instead if not minimum_calls <= call_count <= maximum_calls: messages = ["Expected between {} and {} calls, {} were made.\n\n".format( minimum_calls, maximum_calls, call_count, )] for method_name, capture_fn in mocks.items(): stack_counter = capture_fn.stack_counter messages.append("{!r} was called {} times:\n".format( method_name, stack_counter.total_calls )) for stack in stack_counter: messages.append(" called {} times:\n\n".format(stack_counter.stack_calls(stack))) messages.append(" " + " ".join(traceback.format_list(stack))) messages.append("\n\n") if include_arguments: for (args, kwargs), count in stack_counter[stack].items(): messages.append(" called {} times with:\n".format(count)) messages.append(" args: {}\n".format(args)) messages.append(" kwargs: {}\n\n".format(dict(kwargs))) print "".join(messages) # verify the counter actually worked by ensuring we have counted greater than (or equal to) the minimum calls assert_greater_equal(call_count, minimum_calls) # now verify the number of actual calls is less than (or equal to) the expected maximum assert_less_equal(call_count, maximum_calls) def mongo_uses_error_check(store): """ Does mongo use the error check as a separate message? """ if hasattr(store, 'mongo_wire_version'): return store.mongo_wire_version() <= 1 if hasattr(store, 'modulestores'): return any([mongo_uses_error_check(substore) for substore in store.modulestores]) return False @contextmanager def check_mongo_calls_range(max_finds=float("inf"), min_finds=0, max_sends=None, min_sends=None): """ Instruments the given store to count the number of calls to find (incl find_one) and the number of calls to send_message which is for insert, update, and remove (if you provide num_sends). At the end of the with statement, it compares the counts to the bounds provided in the arguments. :param max_finds: the maximum number of find calls expected :param min_finds: the minimum number of find calls expected :param max_sends: If non-none, make sure number of send calls are <=max_sends :param min_sends: If non-none, make sure number of send calls are >=min_sends """ with check_sum_of_calls( pymongo.message, ['query', 'get_more'], max_finds, min_finds, ): if max_sends is not None or min_sends is not None: with check_sum_of_calls( pymongo.message, # mongo < 2.6 uses insert, update, delete and _do_batched_insert. >= 2.6 _do_batched_write ['insert', 'update', 'delete', '_do_batched_write_command', '_do_batched_insert', ], max_sends if max_sends is not None else float("inf"), min_sends if min_sends is not None else 0, ): yield else: yield @contextmanager def check_mongo_calls(num_finds=0, num_sends=None): """ Instruments the given store to count the number of calls to find (incl find_one) and the number of calls to send_message which is for insert, update, and remove (if you provide num_sends). At the end of the with statement, it compares the counts to the num_finds and num_sends. :param num_finds: the exact number of find calls expected :param num_sends: If none, don't instrument the send calls. If non-none, count and compare to the given int value. """ with check_mongo_calls_range(num_finds, num_finds, num_sends, num_sends): yield # This dict represents the attribute keys for a course's 'about' info. # Note: The 'video' attribute is intentionally excluded as it must be # handled separately; its value maps to an alternate key name. # Reference : from openedx.core.djangoapps.models.course_details.py ABOUT_ATTRIBUTES = { 'effort': "Testing effort", } class CourseAboutFactory(XModuleFactory): """ Factory for XModule course about. """ @classmethod def _create(cls, target_class, **kwargs): # pylint: disable=unused-argument """ Uses **kwargs: effort: effor information video : video link """ user_id = kwargs.pop('user_id', None) course_id, course_runtime = kwargs.pop("course_id"), kwargs.pop("course_runtime") store = kwargs.pop('modulestore') for about_key in ABOUT_ATTRIBUTES: about_item = store.create_xblock(course_runtime, course_id, 'about', about_key) about_item.data = ABOUT_ATTRIBUTES[about_key] store.update_item(about_item, user_id, allow_not_found=True) about_item = store.create_xblock(course_runtime, course_id, 'about', 'video') about_item.data = "www.youtube.com/embed/testing-video-link" store.update_item(about_item, user_id, allow_not_found=True)
jfhumann/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/py/py/_process/forkedfunc.py
271
""" ForkedFunc provides a way to run a function in a forked process and get at its return value, stdout and stderr output as well as signals and exitstatusus. """ import py import os import sys import marshal def get_unbuffered_io(fd, filename): f = open(str(filename), "w") if fd != f.fileno(): os.dup2(f.fileno(), fd) class AutoFlush: def write(self, data): f.write(data) f.flush() def __getattr__(self, name): return getattr(f, name) return AutoFlush() class ForkedFunc: EXITSTATUS_EXCEPTION = 3 def __init__(self, fun, args=None, kwargs=None, nice_level=0, child_on_start=None, child_on_exit=None): if args is None: args = [] if kwargs is None: kwargs = {} self.fun = fun self.args = args self.kwargs = kwargs self.tempdir = tempdir = py.path.local.mkdtemp() self.RETVAL = tempdir.ensure('retval') self.STDOUT = tempdir.ensure('stdout') self.STDERR = tempdir.ensure('stderr') pid = os.fork() if pid: # in parent process self.pid = pid else: # in child process self.pid = None self._child(nice_level, child_on_start, child_on_exit) def _child(self, nice_level, child_on_start, child_on_exit): # right now we need to call a function, but first we need to # map all IO that might happen sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT) sys.stderr = stderr = get_unbuffered_io(2, self.STDERR) retvalf = self.RETVAL.open("wb") EXITSTATUS = 0 try: if nice_level: os.nice(nice_level) try: if child_on_start is not None: child_on_start() retval = self.fun(*self.args, **self.kwargs) retvalf.write(marshal.dumps(retval)) if child_on_exit is not None: child_on_exit() except: excinfo = py.code.ExceptionInfo() stderr.write(str(excinfo._getreprcrash())) EXITSTATUS = self.EXITSTATUS_EXCEPTION finally: stdout.close() stderr.close() retvalf.close() os.close(1) os.close(2) os._exit(EXITSTATUS) def waitfinish(self, waiter=os.waitpid): pid, systemstatus = waiter(self.pid, 0) if systemstatus: if os.WIFSIGNALED(systemstatus): exitstatus = os.WTERMSIG(systemstatus) + 128 else: exitstatus = os.WEXITSTATUS(systemstatus) else: exitstatus = 0 signal = systemstatus & 0x7f if not exitstatus and not signal: retval = self.RETVAL.open('rb') try: retval_data = retval.read() finally: retval.close() retval = marshal.loads(retval_data) else: retval = None stdout = self.STDOUT.read() stderr = self.STDERR.read() self._removetemp() return Result(exitstatus, signal, retval, stdout, stderr) def _removetemp(self): if self.tempdir.check(): self.tempdir.remove() def __del__(self): if self.pid is not None: # only clean up in main process self._removetemp() class Result(object): def __init__(self, exitstatus, signal, retval, stdout, stderr): self.exitstatus = exitstatus self.signal = signal self.retval = retval self.out = stdout self.err = stderr
jodosh/EQ-Tools
refs/heads/master
WardHarvest/makeSignup.py
1
import csv startHTML00 = "<html>\n<head>\n<meta charset=\"UTF-8\">\n<title>Ward Harvest Signup</title>\n<style type=text/css>\ntable.gridtable {\nfont-family: verdana,arial,sans-serif;\nfont-size:16px;\ncolor:#333333;\nborder-width: 1px;\n" startHTML01 = "border-color: #666666;\nborder-collapse: collapse;\nwidth:95%;\nmargin-top:10px;\n}\ntable.gridtable th {\nborder-width: 1px;\npadding: 8px;\nborder-style: solid;\nborder-color: #666666;\n" startHTML02 = "\n}\ntable.gridtable td {\nborder-width: 1px;\npadding: 8px;\nborder-style: solid;\nborder-color: #666666;\n\nwidth: 50%;\n}\n" startHTML03 = "table.gridtable tr:nth-child(even) {\nfont-size:16px;\nbackground-color:#CCC;\n}\n</style>\n<style type=\"text/css\">\ntable { page-break-inside:avoid }\ntr { page-break-inside:avoid; page-break-after:avoid }\n" startHTML04 = "</style>\n</head>\n<body>\n" endHTML = "</table></body>" tableStart = "<table class=gridtable>\n<tr><td>Assignment</td><td>Assigned To</td></tr>\n" tableMiddle = "" f = open('signup.html', 'w') f.write(startHTML00) f.write(startHTML01) f.write(startHTML02) f.write(startHTML03) f.write(startHTML04) with open('Sheet1.tsv', 'rb') as csvFile: reader = csv.reader(csvFile, delimiter='\t') for row in reader: tableMiddle += "<tr><td>" tableMiddle += row[0] + "," + row[1] tableMiddle += "</td><td>" tableMiddle += "&nbsp;" tableMiddle += "</td></tr>\n" f.write(tableStart) f.write(tableMiddle) f.write("</table>") f.write(endHTML) csvFile.close() f.close() # you can omit in most cases as the destructor will call it
rcbops/quantum-buildpackage
refs/heads/master
quantum/wsgi.py
2
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # 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. """ Utility methods for working with WSGI servers """ import logging import sys import eventlet.wsgi eventlet.patcher.monkey_patch(all=False, socket=True) import routes.middleware import webob.dec import webob.exc from lxml import etree from xml.dom import minidom from xml.parsers import expat from quantum.common import exceptions as exception from quantum.common import utils LOG = logging.getLogger('quantum.common.wsgi') class WritableLogger(object): """A thin wrapper that responds to `write` and logs.""" def __init__(self, logger, level=logging.DEBUG): self.logger = logger self.level = level def write(self, msg): self.logger.log(self.level, msg.strip("\n")) def run_server(application, port): """Run a WSGI server with the given application.""" sock = eventlet.listen(('0.0.0.0', port)) eventlet.wsgi.server(sock, application) class Server(object): """Server class to manage multiple WSGI sockets and applications.""" def __init__(self, name, threads=1000): self.pool = eventlet.GreenPool(threads) self.name = name def start(self, application, port, host='0.0.0.0', backlog=128): """Run a WSGI server with the given application.""" socket = eventlet.listen((host, port), backlog=backlog) self.pool.spawn_n(self._run, application, socket) def wait(self): """Wait until all servers have completed running.""" try: self.pool.waitall() except KeyboardInterrupt: pass def _run(self, application, socket): """Start a WSGI server in a new green thread.""" logger = logging.getLogger('eventlet.wsgi.server') eventlet.wsgi.server(socket, application, custom_pool=self.pool, log=WritableLogger(logger)) class Middleware(object): """ Base WSGI middleware wrapper. These classes require an application to be initialized that will be called next. By default the middleware will simply call its wrapped app, or you can override __call__ to customize its behavior. """ def __init__(self, application): self.application = application def process_request(self, req): """ Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here. """ return None def process_response(self, response): """Do whatever you'd like to the response.""" return response @webob.dec.wsgify def __call__(self, req): response = self.process_request(req) if response: return response response = req.get_response(self.application) return self.process_response(response) class Request(webob.Request): def best_match_content_type(self): """Determine the most acceptable content-type. Based on: 1) URI extension (.json/.xml) 2) Content-type header 3) Accept* headers """ # First lookup http request parts = self.path.rsplit('.', 1) if len(parts) > 1: format = parts[1] if format in ['json', 'xml']: return 'application/{0}'.format(parts[1]) #Then look up content header type_from_header = self.get_content_type() if type_from_header: return type_from_header ctypes = ['application/json', 'application/xml'] #Finally search in Accept-* headers bm = self.accept.best_match(ctypes) return bm or 'application/json' def get_content_type(self): allowed_types = ("application/xml", "application/json") if not "Content-Type" in self.headers: LOG.debug(_("Missing Content-Type")) return None type = self.content_type if type in allowed_types: return type return None class ActionDispatcher(object): """Maps method name to local methods through action name.""" def dispatch(self, *args, **kwargs): """Find and call local method.""" action = kwargs.pop('action', 'default') action_method = getattr(self, str(action), self.default) return action_method(*args, **kwargs) def default(self, data): raise NotImplementedError() class DictSerializer(ActionDispatcher): """Default request body serialization""" def serialize(self, data, action='default'): return self.dispatch(data, action=action) def default(self, data): return "" class JSONDictSerializer(DictSerializer): """Default JSON request body serialization""" def default(self, data): return utils.dumps(data) class XMLDictSerializer(DictSerializer): def __init__(self, metadata=None, xmlns=None): """ :param metadata: information needed to deserialize xml into a dictionary. :param xmlns: XML namespace to include with serialized xml """ super(XMLDictSerializer, self).__init__() self.metadata = metadata or {} self.xmlns = xmlns def default(self, data): # We expect data to contain a single key which is the XML root. root_key = data.keys()[0] doc = minidom.Document() node = self._to_xml_node(doc, self.metadata, root_key, data[root_key]) return self.to_xml_string(node) def to_xml_string(self, node, has_atom=False): self._add_xmlns(node, has_atom) return node.toxml('UTF-8') #NOTE (ameade): the has_atom should be removed after all of the # xml serializers and view builders have been updated to the current # spec that required all responses include the xmlns:atom, the has_atom # flag is to prevent current tests from breaking def _add_xmlns(self, node, has_atom=False): if self.xmlns is not None: node.setAttribute('xmlns', self.xmlns) if has_atom: node.setAttribute('xmlns:atom', "http://www.w3.org/2005/Atom") def _to_xml_node(self, doc, metadata, nodename, data): """Recursive method to convert data members to XML nodes.""" result = doc.createElement(nodename) # Set the xml namespace if one is specified # TODO(justinsb): We could also use prefixes on the keys xmlns = metadata.get('xmlns', None) if xmlns: result.setAttribute('xmlns', xmlns) #TODO(bcwaldon): accomplish this without a type-check if isinstance(data, list): collections = metadata.get('list_collections', {}) if nodename in collections: metadata = collections[nodename] for item in data: node = doc.createElement(metadata['item_name']) node.setAttribute(metadata['item_key'], str(item)) result.appendChild(node) return result singular = metadata.get('plurals', {}).get(nodename, None) if singular is None: if nodename.endswith('s'): singular = nodename[:-1] else: singular = 'item' for item in data: node = self._to_xml_node(doc, metadata, singular, item) result.appendChild(node) #TODO(bcwaldon): accomplish this without a type-check elif isinstance(data, dict): collections = metadata.get('dict_collections', {}) if nodename in collections: metadata = collections[nodename] for k, v in data.items(): node = doc.createElement(metadata['item_name']) node.setAttribute(metadata['item_key'], str(k)) text = doc.createTextNode(str(v)) node.appendChild(text) result.appendChild(node) return result attrs = metadata.get('attributes', {}).get(nodename, {}) for k, v in data.items(): if k in attrs: result.setAttribute(k, str(v)) else: node = self._to_xml_node(doc, metadata, k, v) result.appendChild(node) else: # Type is atom node = doc.createTextNode(str(data)) result.appendChild(node) return result def _create_link_nodes(self, xml_doc, links): link_nodes = [] for link in links: link_node = xml_doc.createElement('atom:link') link_node.setAttribute('rel', link['rel']) link_node.setAttribute('href', link['href']) if 'type' in link: link_node.setAttribute('type', link['type']) link_nodes.append(link_node) return link_nodes def _to_xml(self, root): """Convert the xml object to an xml string.""" return etree.tostring(root, encoding='UTF-8', xml_declaration=True) class ResponseHeaderSerializer(ActionDispatcher): """Default response headers serialization""" def serialize(self, response, data, action): self.dispatch(response, data, action=action) def default(self, response, data): response.status_int = 200 class ResponseSerializer(object): """Encode the necessary pieces into a response object""" def __init__(self, body_serializers=None, headers_serializer=None): self.body_serializers = { 'application/xml': XMLDictSerializer(), 'application/json': JSONDictSerializer(), } self.body_serializers.update(body_serializers or {}) self.headers_serializer = headers_serializer or \ ResponseHeadersSerializer() def serialize(self, response_data, content_type, action='default'): """Serialize a dict into a string and wrap in a wsgi.Request object. :param response_data: dict produced by the Controller :param content_type: expected mimetype of serialized response body """ response = webob.Response() self.serialize_headers(response, response_data, action) self.serialize_body(response, response_data, content_type, action) return response def serialize_headers(self, response, data, action): self.headers_serializer.serialize(response, data, action) def serialize_body(self, response, data, content_type, action): response.headers['Content-Type'] = content_type if data is not None: serializer = self.get_body_serializer(content_type) response.body = serializer.serialize(data, action) def get_body_serializer(self, content_type): try: return self.body_serializers[content_type] except (KeyError, TypeError): raise exception.InvalidContentType(content_type=content_type) class TextDeserializer(ActionDispatcher): """Default request body deserialization""" def deserialize(self, datastring, action='default'): return self.dispatch(datastring, action=action) def default(self, datastring): return {} class JSONDeserializer(TextDeserializer): def _from_json(self, datastring): try: return utils.loads(datastring) except ValueError: msg = _("cannot understand JSON") raise exception.MalformedRequestBody(reason=msg) def default(self, datastring): return {'body': self._from_json(datastring)} class XMLDeserializer(TextDeserializer): def __init__(self, metadata=None): """ :param metadata: information needed to deserialize xml into a dictionary. """ super(XMLDeserializer, self).__init__() self.metadata = metadata or {} def _from_xml(self, datastring): plurals = set(self.metadata.get('plurals', {})) try: node = minidom.parseString(datastring).childNodes[0] return {node.nodeName: self._from_xml_node(node, plurals)} except expat.ExpatError: msg = _("cannot understand XML") raise exception.MalformedRequestBody(reason=msg) def _from_xml_node(self, node, listnames): """Convert a minidom node to a simple Python type. :param listnames: list of XML node names whose subnodes should be considered list items. """ if len(node.childNodes) == 1 and node.childNodes[0].nodeType == 3: return node.childNodes[0].nodeValue elif node.nodeName in listnames: return [self._from_xml_node(n, listnames) for n in node.childNodes] else: result = dict() for attr in node.attributes.keys(): result[attr] = node.attributes[attr].nodeValue for child in node.childNodes: if child.nodeType != node.TEXT_NODE: result[child.nodeName] = self._from_xml_node(child, listnames) return result def find_first_child_named(self, parent, name): """Search a nodes children for the first child with a given name""" for node in parent.childNodes: if node.nodeName == name: return node return None def find_children_named(self, parent, name): """Return all of a nodes children who have the given name""" for node in parent.childNodes: if node.nodeName == name: yield node def extract_text(self, node): """Get the text field contained by the given node""" if len(node.childNodes) == 1: child = node.childNodes[0] if child.nodeType == child.TEXT_NODE: return child.nodeValue return "" def default(self, datastring): return {'body': self._from_xml(datastring)} class RequestHeadersDeserializer(ActionDispatcher): """Default request headers deserializer""" def deserialize(self, request, action): return self.dispatch(request, action=action) def default(self, request): return {} class RequestDeserializer(object): """Break up a Request object into more useful pieces.""" def __init__(self, body_deserializers=None, headers_deserializer=None): self.body_deserializers = { 'application/xml': XMLDeserializer(), 'application/json': JSONDeserializer(), } self.body_deserializers.update(body_deserializers or {}) self.headers_deserializer = headers_deserializer or \ RequestHeadersDeserializer() def deserialize(self, request): """Extract necessary pieces of the request. :param request: Request object :returns tuple of expected controller action name, dictionary of keyword arguments to pass to the controller, the expected content type of the response """ action_args = self.get_action_args(request.environ) action = action_args.pop('action', None) action_args.update(self.deserialize_headers(request, action)) action_args.update(self.deserialize_body(request, action)) accept = self.get_expected_content_type(request) return (action, action_args, accept) def deserialize_headers(self, request, action): return self.headers_deserializer.deserialize(request, action) def deserialize_body(self, request, action): try: content_type = request.best_match_content_type() except exception.InvalidContentType: LOG.debug(_("Unrecognized Content-Type provided in request")) return {} if content_type is None: LOG.debug(_("No Content-Type provided in request")) return {} if not len(request.body) > 0: LOG.debug(_("Empty body provided in request")) return {} try: deserializer = self.get_body_deserializer(content_type) except exception.InvalidContentType: LOG.debug(_("Unable to deserialize body as provided Content-Type")) raise return deserializer.deserialize(request.body, action) def get_body_deserializer(self, content_type): try: return self.body_deserializers[content_type] except (KeyError, TypeError): raise exception.InvalidContentType(content_type=content_type) def get_expected_content_type(self, request): return request.best_match_content_type() def get_action_args(self, request_environment): """Parse dictionary created by routes library.""" try: args = request_environment['wsgiorg.routing_args'][1].copy() except Exception: return {} try: del args['controller'] except KeyError: pass try: del args['format'] except KeyError: pass return args class Application(object): """Base WSGI application wrapper. Subclasses need to implement __call__.""" @classmethod def factory(cls, global_config, **local_config): """Used for paste app factories in paste.deploy config files. Any local configuration (that is, values under the [app:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs. A hypothetical configuration would look like: [app:wadl] latest_version = 1.3 paste.app_factory = nova.api.fancy_api:Wadl.factory which would result in a call to the `Wadl` class as import quantum.api.fancy_api fancy_api.Wadl(latest_version='1.3') You could of course re-implement the `factory` method in subclasses, but using the kwarg passing it shouldn't be necessary. """ return cls(**local_config) def __call__(self, environ, start_response): r"""Subclasses will probably want to implement __call__ like this: @webob.dec.wsgify(RequestClass=Request) def __call__(self, req): # Any of the following objects work as responses: # Option 1: simple string res = 'message\n' # Option 2: a nicely formatted HTTP exception page res = exc.HTTPForbidden(detail='Nice try') # Option 3: a webob Response object (in case you need to play with # headers, or you want to be treated like an iterable, or or or) res = Response(); res.app_iter = open('somefile') # Option 4: any wsgi app to be run next res = self.application # Option 5: you can get a Response object for a wsgi app, too, to # play with headers etc res = req.get_response(self.application) # You can then just return your response... return res # ... or set req.response and return None. req.response = res See the end of http://pythonpaste.org/webob/modules/dec.html for more info. """ raise NotImplementedError(_('You must implement __call__')) class Debug(Middleware): """ Helper class that can be inserted into any WSGI application chain to get information about the request and response. """ @webob.dec.wsgify def __call__(self, req): print ("*" * 40) + " REQUEST ENVIRON" for key, value in req.environ.items(): print key, "=", value print resp = req.get_response(self.application) print ("*" * 40) + " RESPONSE HEADERS" for (key, value) in resp.headers.iteritems(): print key, "=", value print resp.app_iter = self.print_generator(resp.app_iter) return resp @staticmethod def print_generator(app_iter): """ Iterator that prints the contents of a wrapper string iterator when iterated. """ print ("*" * 40) + " BODY" for part in app_iter: sys.stdout.write(part) sys.stdout.flush() yield part print class Router(object): """ WSGI middleware that maps incoming requests to WSGI apps. """ @classmethod def factory(cls, global_config, **local_config): """ Returns an instance of the WSGI Router class """ return cls() def __init__(self, mapper): """ Create a router for the given routes.Mapper. Each route in `mapper` must specify a 'controller', which is a WSGI app to call. You'll probably want to specify an 'action' as well and have your controller be a wsgi.Controller, who will route the request to the action method. Examples: mapper = routes.Mapper() sc = ServerController() # Explicit mapping of one route to a controller+action mapper.connect(None, "/svrlist", controller=sc, action="list") # Actions are all implicitly defined mapper.resource("network", "networks", controller=nc) # Pointing to an arbitrary WSGI app. You can specify the # {path_info:.*} parameter so the target app can be handed just that # section of the URL. mapper.connect(None, "/v1.0/{path_info:.*}", controller=BlogApp()) """ self.map = mapper self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.map) @webob.dec.wsgify def __call__(self, req): """ Route the incoming request to a controller based on self.map. If no match, return a 404. """ return self._router @staticmethod @webob.dec.wsgify def _dispatch(req): """ Called by self._router after matching the incoming request to a route and putting the information into req.environ. Either returns 404 or the routed WSGI app's response. """ match = req.environ['wsgiorg.routing_args'][1] if not match: return webob.exc.HTTPNotFound() app = match['controller'] return app class Resource(Application): """WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Request. If the operation is a PUT or POST, the controller method must also accept a 'body' argument (the deserialized request body). They may raise a webob.exc exception or return a dict, which will be serialized by requested content type. """ def __init__(self, controller, fault_body_function, deserializer=None, serializer=None): """ :param controller: object that implement methods created by routes lib :param deserializer: object that can serialize the output of a controller into a webob response :param serializer: object that can deserialize a webob request into necessary pieces :param fault_body_function: a function that will build the response body for HTTP errors raised by operations on this resource object """ self.controller = controller self.deserializer = deserializer or RequestDeserializer() self.serializer = serializer or ResponseSerializer() self._fault_body_function = fault_body_function # use serializer's xmlns for populating Fault generator xmlns xml_serializer = self.serializer.body_serializers['application/xml'] if hasattr(xml_serializer, 'xmlns'): self._xmlns = xml_serializer.xmlns @webob.dec.wsgify(RequestClass=Request) def __call__(self, request): """WSGI method that controls (de)serialization and method dispatch.""" LOG.info("%(method)s %(url)s" % {"method": request.method, "url": request.url}) try: action, args, accept = self.deserializer.deserialize(request) except exception.InvalidContentType: msg = _("Unsupported Content-Type") LOG.exception("InvalidContentType:%s", msg) return Fault(webob.exc.HTTPBadRequest(explanation=msg), self._xmlns) except exception.MalformedRequestBody: msg = _("Malformed request body") LOG.exception("MalformedRequestBody:%s", msg) return Fault(webob.exc.HTTPBadRequest(explanation=msg), self._xmlns) try: action_result = self.dispatch(request, action, args) except webob.exc.HTTPException as ex: LOG.info(_("HTTP exception thrown: %s"), unicode(ex)) action_result = Fault(ex, self._xmlns, self._fault_body_function) if isinstance(action_result, dict) or action_result is None: response = self.serializer.serialize(action_result, accept, action=action) else: response = action_result try: msg_dict = dict(url=request.url, status=response.status_int) msg = _("%(url)s returned with HTTP %(status)d") % msg_dict except AttributeError, e: msg_dict = dict(url=request.url, e=e) msg = _("%(url)s returned a fault: %(e)s" % msg_dict) LOG.info(msg) return response def dispatch(self, request, action, action_args): """Find action-spefic method on controller and call it.""" controller_method = getattr(self.controller, action) try: #NOTE(salvatore-orlando): the controller method must have # an argument whose name is 'request' return controller_method(request=request, **action_args) except TypeError as exc: LOG.exception(exc) return Fault(webob.exc.HTTPBadRequest(), self._xmlns) def _default_body_function(wrapped_exc): code = wrapped_exc.status_int fault_data = { 'Error': { 'code': code, 'message': wrapped_exc.explanation}} # 'code' is an attribute on the fault tag itself metadata = {'attributes': {'Error': 'code'}} return fault_data, metadata class Fault(webob.exc.HTTPException): """ Generates an HTTP response from a webob HTTP exception""" def __init__(self, exception, xmlns=None, body_function=None): """Creates a Fault for the given webob.exc.exception.""" self.wrapped_exc = exception self.status_int = self.wrapped_exc.status_int self._xmlns = xmlns self._body_function = body_function or _default_body_function @webob.dec.wsgify(RequestClass=Request) def __call__(self, req): """Generate a WSGI response based on the exception passed to ctor.""" # Replace the body with fault details. fault_data, metadata = self._body_function(self.wrapped_exc) xml_serializer = XMLDictSerializer(metadata, self._xmlns) content_type = req.best_match_content_type() serializer = { 'application/xml': xml_serializer, 'application/json': JSONDictSerializer(), }[content_type] self.wrapped_exc.body = serializer.serialize(fault_data) self.wrapped_exc.content_type = content_type return self.wrapped_exc # NOTE(salvatore-orlando): this class will go once the # extension API framework is updated class Controller(object): """WSGI app that dispatched to methods. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon itself. All action methods must, in addition to their normal parameters, accept a 'req' argument which is the incoming wsgi.Request. They raise a webob.exc exception, or return a dict which will be serialized by requested content type. """ @webob.dec.wsgify(RequestClass=Request) def __call__(self, req): """ Call the method specified in req.environ by RoutesMiddleware. """ arg_dict = req.environ['wsgiorg.routing_args'][1] action = arg_dict['action'] method = getattr(self, action) del arg_dict['controller'] del arg_dict['action'] if 'format' in arg_dict: del arg_dict['format'] arg_dict['request'] = req result = method(**arg_dict) if isinstance(result, dict): content_type = req.best_match_content_type() default_xmlns = self.get_default_xmlns(req) body = self._serialize(result, content_type, default_xmlns) response = webob.Response() response.headers['Content-Type'] = content_type response.body = body msg_dict = dict(url=req.url, status=response.status_int) msg = _("%(url)s returned with HTTP %(status)d") % msg_dict LOG.debug(msg) return response else: return result def _serialize(self, data, content_type, default_xmlns): """Serialize the given dict to the provided content_type. Uses self._serialization_metadata if it exists, which is a dict mapping MIME types to information needed to serialize to that type. """ _metadata = getattr(type(self), '_serialization_metadata', {}) serializer = Serializer(_metadata, default_xmlns) try: return serializer.serialize(data, content_type) except exception.InvalidContentType: raise webob.exc.HTTPNotAcceptable() def _deserialize(self, data, content_type): """Deserialize the request body to the specefied content type. Uses self._serialization_metadata if it exists, which is a dict mapping MIME types to information needed to serialize to that type. """ _metadata = getattr(type(self), '_serialization_metadata', {}) serializer = Serializer(_metadata) return serializer.deserialize(data, content_type) def get_default_xmlns(self, req): """Provide the XML namespace to use if none is otherwise specified.""" return None # NOTE(salvatore-orlando): this class will go once the # extension API framework is updated class Serializer(object): """Serializes and deserializes dictionaries to certain MIME types.""" def __init__(self, metadata=None, default_xmlns=None): """Create a serializer based on the given WSGI environment. 'metadata' is an optional dict mapping MIME types to information needed to serialize a dictionary to that type. """ self.metadata = metadata or {} self.default_xmlns = default_xmlns def _get_serialize_handler(self, content_type): handlers = { 'application/json': self._to_json, 'application/xml': self._to_xml, } try: return handlers[content_type] except Exception: raise exception.InvalidContentType(content_type=content_type) def serialize(self, data, content_type): """Serialize a dictionary into the specified content type.""" return self._get_serialize_handler(content_type)(data) def deserialize(self, datastring, content_type): """Deserialize a string to a dictionary. The string must be in the format of a supported MIME type. """ try: return self.get_deserialize_handler(content_type)(datastring) except Exception: raise webob.exc.HTTPBadRequest("Could not deserialize data") def get_deserialize_handler(self, content_type): handlers = { 'application/json': self._from_json, 'application/xml': self._from_xml, } try: return handlers[content_type] except Exception: raise exception.InvalidContentType(content_type=content_type) def _from_json(self, datastring): return utils.loads(datastring) def _from_xml(self, datastring): xmldata = self.metadata.get('application/xml', {}) plurals = set(xmldata.get('plurals', {})) node = minidom.parseString(datastring).childNodes[0] return {node.nodeName: self._from_xml_node(node, plurals)} def _from_xml_node(self, node, listnames): """Convert a minidom node to a simple Python type. listnames is a collection of names of XML nodes whose subnodes should be considered list items. """ if len(node.childNodes) == 1 and node.childNodes[0].nodeType == 3: return node.childNodes[0].nodeValue elif node.nodeName in listnames: return [self._from_xml_node(n, listnames) for n in node.childNodes if n.nodeType != node.TEXT_NODE] else: result = dict() for attr in node.attributes.keys(): result[attr] = node.attributes[attr].nodeValue for child in node.childNodes: if child.nodeType != node.TEXT_NODE: result[child.nodeName] = self._from_xml_node(child, listnames) return result def _to_json(self, data): return utils.dumps(data) def _to_xml(self, data): metadata = self.metadata.get('application/xml', {}) # We expect data to contain a single key which is the XML root. root_key = data.keys()[0] doc = minidom.Document() node = self._to_xml_node(doc, metadata, root_key, data[root_key]) xmlns = node.getAttribute('xmlns') if not xmlns and self.default_xmlns: node.setAttribute('xmlns', self.default_xmlns) return node.toprettyxml(indent='', newl='') def _to_xml_node(self, doc, metadata, nodename, data): """Recursive method to convert data members to XML nodes.""" result = doc.createElement(nodename) # Set the xml namespace if one is specified # TODO(justinsb): We could also use prefixes on the keys xmlns = metadata.get('xmlns', None) if xmlns: result.setAttribute('xmlns', xmlns) if isinstance(data, list): collections = metadata.get('list_collections', {}) if nodename in collections: metadata = collections[nodename] for item in data: node = doc.createElement(metadata['item_name']) node.setAttribute(metadata['item_key'], str(item)) result.appendChild(node) return result singular = metadata.get('plurals', {}).get(nodename, None) if singular is None: if nodename.endswith('s'): singular = nodename[:-1] else: singular = 'item' for item in data: node = self._to_xml_node(doc, metadata, singular, item) result.appendChild(node) elif isinstance(data, dict): collections = metadata.get('dict_collections', {}) if nodename in collections: metadata = collections[nodename] for k, v in data.items(): node = doc.createElement(metadata['item_name']) node.setAttribute(metadata['item_key'], str(k)) text = doc.createTextNode(str(v)) node.appendChild(text) result.appendChild(node) return result attrs = metadata.get('attributes', {}).get(nodename, {}) for k, v in data.items(): if k in attrs: result.setAttribute(k, str(v)) else: node = self._to_xml_node(doc, metadata, k, v) result.appendChild(node) else: # Type is atom. node = doc.createTextNode(str(data)) result.appendChild(node) return result
drewandersonnz/openshift-tools
refs/heads/prod
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/ansible/oc_serviceaccount.py
86
# pylint: skip-file # flake8: noqa def main(): ''' ansible oc module for service accounts ''' module = AnsibleModule( argument_spec=dict( kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'absent', 'list']), debug=dict(default=False, type='bool'), name=dict(default=None, required=True, type='str'), namespace=dict(default=None, required=True, type='str'), secrets=dict(default=None, type='list'), image_pull_secrets=dict(default=None, type='list'), ), supports_check_mode=True, ) rval = OCServiceAccount.run_ansible(module.params, module.check_mode) if 'failed' in rval: module.fail_json(**rval) module.exit_json(**rval) if __name__ == '__main__': main()
pixelgremlins/ztruck
refs/heads/master
dj/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/big5prober.py
2930
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library 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 2.1 of the License, or (at your option) any later version. # # This library 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 this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import Big5DistributionAnalysis from .mbcssm import Big5SMModel class Big5Prober(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(Big5SMModel) self._mDistributionAnalyzer = Big5DistributionAnalysis() self.reset() def get_charset_name(self): return "Big5"
aethaniel/micropython
refs/heads/master
tests/basics/closure1.py
119
# closures def f(x): y = 2 * x def g(z): return y + z return g print(f(1)(1)) x = f(2) y = f(3) print(x(1), x(2), x(3)) print(y(1), y(2), y(3)) print(x(1), x(2), x(3)) print(y(1), y(2), y(3))
ABaldwinHunter/flask-clone-classic
refs/heads/master
docs/conf.py
140
# -*- coding: utf-8 -*- # # Flask documentation build configuration file, created by # sphinx-quickstart on Tue Apr 6 15:24:58 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath('_themes')) sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'flaskdocext'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Flask' copyright = u'2015, Armin Ronacher' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. import pkg_resources try: release = pkg_resources.get_distribution('Flask').version except pkg_resources.DistributionNotFound: print 'To build the documentation, The distribution information of Flask' print 'Has to be available. Either install the package into your' print 'development environment or run "setup.py develop" to setup the' print 'metadata. A virtualenv is recommended!' sys.exit(1) del pkg_resources if 'dev' in release: release = release.split('dev')[0] + 'dev' version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'flask' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'touch_icon': 'touch-icon.png' } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. Do not set, template magic! #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = "flask-favicon.ico" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'], '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'] } # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_use_modindex = False # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Flaskdoc' # -- Options for LaTeX output -------------------------------------------------- # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'), ] # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_use_modindex = False latex_elements = { 'fontpkg': r'\usepackage{mathpazo}', 'papersize': 'a4paper', 'pointsize': '12pt', 'preamble': r'\usepackage{flaskstyle}' } latex_use_parts = True latex_additional_files = ['flaskstyle.sty', 'logo.pdf'] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. #epub_title = '' #epub_author = '' #epub_publisher = '' #epub_copyright = '' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 intersphinx_mapping = { 'https://docs.python.org/dev': None, 'http://werkzeug.pocoo.org/docs/': None, 'http://click.pocoo.org/': None, 'http://jinja.pocoo.org/docs/': None, 'http://www.sqlalchemy.org/docs/': None, 'https://wtforms.readthedocs.org/en/latest/': None, 'https://pythonhosted.org/blinker/': None } pygments_style = 'flask_theme_support.FlaskyStyle' # fall back if theme is not there try: __import__('flask_theme_support') except ImportError, e: print '-' * 74 print 'Warning: Flask themes unavailable. Building with default theme' print 'If you want the Flask themes, run this command and build again:' print print ' git submodule update --init' print '-' * 74 pygments_style = 'tango' html_theme = 'default' html_theme_options = {} # unwrap decorators def unwrap_decorators(): import sphinx.util.inspect as inspect import functools old_getargspec = inspect.getargspec def getargspec(x): return old_getargspec(getattr(x, '_original_function', x)) inspect.getargspec = getargspec old_update_wrapper = functools.update_wrapper def update_wrapper(wrapper, wrapped, *a, **kw): rv = old_update_wrapper(wrapper, wrapped, *a, **kw) rv._original_function = wrapped return rv functools.update_wrapper = update_wrapper unwrap_decorators() del unwrap_decorators
ehashman/oh-mainline
refs/heads/master
vendor/packages/scrapy/scrapy/xlib/pydispatch/saferef.py
25
"""Refactored "safe reference" from dispatcher.py""" import weakref, traceback def safeRef(target, onDelete = None): """Return a *safe* weak reference to a callable target target -- the object to be weakly referenced, if it's a bound method reference, will create a BoundMethodWeakref, otherwise creates a simple weakref. onDelete -- if provided, will have a hard reference stored to the callable to be called after the safe reference goes out of scope with the reference object, (either a weakref or a BoundMethodWeakref) as argument. """ if hasattr(target, 'im_self'): if target.im_self is not None: # Turn a bound method into a BoundMethodWeakref instance. # Keep track of these instances for lookup by disconnect(). assert hasattr(target, 'im_func'), """safeRef target %r has im_self, but no im_func, don't know how to create reference"""%( target,) reference = BoundMethodWeakref( target=target, onDelete=onDelete ) return reference if onDelete is not None: return weakref.ref(target, onDelete) else: return weakref.ref( target ) class BoundMethodWeakref(object): """'Safe' and reusable weak references to instance methods BoundMethodWeakref objects provide a mechanism for referencing a bound method without requiring that the method object itself (which is normally a transient object) is kept alive. Instead, the BoundMethodWeakref object keeps weak references to both the object and the function which together define the instance method. Attributes: key -- the identity key for the reference, calculated by the class's calculateKey method applied to the target instance method deletionMethods -- sequence of callable objects taking single argument, a reference to this object which will be called when *either* the target object or target function is garbage collected (i.e. when this object becomes invalid). These are specified as the onDelete parameters of safeRef calls. weakSelf -- weak reference to the target object weakFunc -- weak reference to the target function Class Attributes: _allInstances -- class attribute pointing to all live BoundMethodWeakref objects indexed by the class's calculateKey(target) method applied to the target objects. This weak value dictionary is used to short-circuit creation so that multiple references to the same (object, function) pair produce the same BoundMethodWeakref instance. """ _allInstances = weakref.WeakValueDictionary() def __new__( cls, target, onDelete=None, *arguments,**named ): """Create new instance or return current instance Basically this method of construction allows us to short-circuit creation of references to already- referenced instance methods. The key corresponding to the target is calculated, and if there is already an existing reference, that is returned, with its deletionMethods attribute updated. Otherwise the new instance is created and registered in the table of already-referenced methods. """ key = cls.calculateKey(target) current =cls._allInstances.get(key) if current is not None: current.deletionMethods.append( onDelete) return current else: base = super( BoundMethodWeakref, cls).__new__( cls ) cls._allInstances[key] = base base.__init__( target, onDelete, *arguments,**named) return base def __init__(self, target, onDelete=None): """Return a weak-reference-like instance for a bound method target -- the instance-method target for the weak reference, must have im_self and im_func attributes and be reconstructable via: target.im_func.__get__( target.im_self ) which is true of built-in instance methods. onDelete -- optional callback which will be called when this weak reference ceases to be valid (i.e. either the object or the function is garbage collected). Should take a single argument, which will be passed a pointer to this object. """ def remove(weak, self=self): """Set self.isDead to true when method or instance is destroyed""" methods = self.deletionMethods[:] del self.deletionMethods[:] try: del self.__class__._allInstances[ self.key ] except KeyError: pass for function in methods: try: if callable( function ): function( self ) except Exception, e: try: traceback.print_exc() except AttributeError, err: print '''Exception during saferef %s cleanup function %s: %s'''%( self, function, e ) self.deletionMethods = [onDelete] self.key = self.calculateKey( target ) self.weakSelf = weakref.ref(target.im_self, remove) self.weakFunc = weakref.ref(target.im_func, remove) self.selfName = target.im_self.__class__.__name__ self.funcName = str(target.im_func.__name__) def calculateKey( cls, target ): """Calculate the reference key for this reference Currently this is a two-tuple of the id()'s of the target object and the target function respectively. """ return (id(target.im_self),id(target.im_func)) calculateKey = classmethod( calculateKey ) def __str__(self): """Give a friendly representation of the object""" return """%s( %s.%s )"""%( self.__class__.__name__, self.selfName, self.funcName, ) __repr__ = __str__ def __nonzero__( self ): """Whether we are still a valid reference""" return self() is not None def __cmp__( self, other ): """Compare with another reference""" if not isinstance (other,self.__class__): return cmp( self.__class__, type(other) ) return cmp( self.key, other.key) def __call__(self): """Return a strong reference to the bound method If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference. """ target = self.weakSelf() if target is not None: function = self.weakFunc() if function is not None: return function.__get__(target) return None
m-kuhn/QGIS
refs/heads/master
tests/src/python/test_qgsproject.py
3
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsProject. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ from builtins import chr from builtins import range __author__ = 'Sebastian Dietrich' __date__ = '19/11/2015' __copyright__ = 'Copyright 2015, The QGIS Project' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os import qgis # NOQA from qgis.core import (QgsProject, QgsCoordinateTransformContext, QgsProjectDirtyBlocker, QgsApplication, QgsUnitTypes, QgsCoordinateReferenceSystem, QgsLabelingEngineSettings, QgsVectorLayer, QgsRasterLayer, QgsMapLayer, QgsExpressionContextUtils, QgsProjectColorScheme) from qgis.gui import (QgsLayerTreeMapCanvasBridge, QgsMapCanvas) from qgis.PyQt.QtTest import QSignalSpy from qgis.PyQt.QtCore import QT_VERSION_STR, QTemporaryDir from qgis.PyQt.QtGui import QColor from qgis.PyQt import sip from qgis.testing import start_app, unittest from utilities import (unitTestDataPath) from shutil import copyfile app = start_app() TEST_DATA_DIR = unitTestDataPath() def createLayer(name): return QgsVectorLayer("Point?field=x:string", name, "memory") class TestQgsProject(unittest.TestCase): def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.messageCaught = False def test_makeKeyTokens_(self): # see http://www.w3.org/TR/REC-xml/#d0e804 for a list of valid characters invalidTokens = [] validTokens = [] # all test tokens will be generated by prepending or inserting characters to this token validBase = "valid" # some invalid characters, not allowed anywhere in a token # note that '/' must not be added here because it is taken as a separator by makeKeyTokens_() invalidChars = "+*,;<>|!$%()=?#\x01" # generate the characters that are allowed at the start of a token (and at every other position) validStartChars = ":_" charRanges = [ (ord('a'), ord('z')), (ord('A'), ord('Z')), (0x00F8, 0x02FF), (0x0370, 0x037D), (0x037F, 0x1FFF), (0x200C, 0x200D), (0x2070, 0x218F), (0x2C00, 0x2FEF), (0x3001, 0xD7FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFFD), # (0x10000, 0xEFFFF), while actually valid, these are not yet accepted by makeKeyTokens_() ] for r in charRanges: for c in range(r[0], r[1]): validStartChars += chr(c) # generate the characters that are only allowed inside a token, not at the start validInlineChars = "-.\xB7" charRanges = [ (ord('0'), ord('9')), (0x0300, 0x036F), (0x203F, 0x2040), ] for r in charRanges: for c in range(r[0], r[1]): validInlineChars += chr(c) # test forbidden start characters for c in invalidChars + validInlineChars: invalidTokens.append(c + validBase) # test forbidden inline characters for c in invalidChars: invalidTokens.append(validBase[:4] + c + validBase[4:]) # test each allowed start character for c in validStartChars: validTokens.append(c + validBase) # test each allowed inline character for c in validInlineChars: validTokens.append(validBase[:4] + c + validBase[4:]) logger = QgsApplication.messageLog() logger.messageReceived.connect(self.catchMessage) prj = QgsProject.instance() for token in validTokens: self.messageCaught = False prj.readEntry("test", token) myMessage = "valid token '%s' not accepted" % (token) assert not self.messageCaught, myMessage for token in invalidTokens: self.messageCaught = False prj.readEntry("test", token) myMessage = "invalid token '%s' accepted" % (token) assert self.messageCaught, myMessage logger.messageReceived.disconnect(self.catchMessage) def catchMessage(self): self.messageCaught = True def testClear(self): prj = QgsProject.instance() prj.setTitle('xxx') spy = QSignalSpy(prj.cleared) prj.clear() self.assertEqual(len(spy), 1) self.assertFalse(prj.title()) def testCrs(self): prj = QgsProject.instance() prj.clear() self.assertFalse(prj.crs().isValid()) prj.setCrs(QgsCoordinateReferenceSystem.fromOgcWmsCrs('EPSG:3111')) self.assertEqual(prj.crs().authid(), 'EPSG:3111') def testEllipsoid(self): prj = QgsProject.instance() prj.clear() prj.setCrs(QgsCoordinateReferenceSystem.fromOgcWmsCrs('EPSG:3111')) prj.setEllipsoid('WGS84') self.assertEqual(prj.ellipsoid(), 'WGS84') # if project has NO crs, then ellipsoid should always be none prj.setCrs(QgsCoordinateReferenceSystem()) self.assertEqual(prj.ellipsoid(), 'NONE') def testDistanceUnits(self): prj = QgsProject.instance() prj.clear() prj.setDistanceUnits(QgsUnitTypes.DistanceFeet) self.assertEqual(prj.distanceUnits(), QgsUnitTypes.DistanceFeet) def testAreaUnits(self): prj = QgsProject.instance() prj.clear() prj.setAreaUnits(QgsUnitTypes.AreaSquareFeet) self.assertEqual(prj.areaUnits(), QgsUnitTypes.AreaSquareFeet) def testReadEntry(self): prj = QgsProject.instance() prj.read(os.path.join(TEST_DATA_DIR, 'labeling/test-labeling.qgs')) # valid key, valid int value self.assertEqual(prj.readNumEntry("SpatialRefSys", "/ProjectionsEnabled", -1)[0], 0) # invalid key self.assertEqual(prj.readNumEntry("SpatialRefSys", "/InvalidKey", -1)[0], -1) def testEmbeddedGroup(self): testdata_path = unitTestDataPath('embedded_groups') + '/' prj_path = os.path.join(testdata_path, "project2.qgs") prj = QgsProject() prj.read(prj_path) layer_tree_group = prj.layerTreeRoot() layers_ids = layer_tree_group.findLayerIds() layers_names = [] for layer_id in layers_ids: name = prj.mapLayer(layer_id).name() layers_names.append(name) expected = ['polys', 'lines'] self.assertEqual(sorted(layers_names), sorted(expected)) def testInstance(self): """ test retrieving global instance """ self.assertTrue(QgsProject.instance()) # register a layer to the singleton QgsProject.instance().addMapLayer(createLayer('test')) # check that the same instance is returned self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) QgsProject.instance().removeAllMapLayers() def test_addMapLayer(self): """ test adding individual map layers to registry """ QgsProject.instance().removeAllMapLayers() l1 = createLayer('test') self.assertEqual(QgsProject.instance().addMapLayer(l1), l1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) # adding a second layer should leave existing layers intact l2 = createLayer('test2') self.assertEqual(QgsProject.instance().addMapLayer(l2), l2) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test2')), 1) self.assertEqual(QgsProject.instance().count(), 2) QgsProject.instance().removeAllMapLayers() def test_addMapLayerAlreadyAdded(self): """ test that already added layers can't be readded to registry """ QgsProject.instance().removeAllMapLayers() l1 = createLayer('test') QgsProject.instance().addMapLayer(l1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) self.assertEqual(QgsProject.instance().addMapLayer(l1), None) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) QgsProject.instance().removeAllMapLayers() def test_addMapLayerInvalid(self): """ test that invalid map layers can be added to registry """ QgsProject.instance().removeAllMapLayers() vl = QgsVectorLayer("Point?field=x:string", 'test', "xxx") self.assertEqual(QgsProject.instance().addMapLayer(vl), vl) self.assertFalse(vl in QgsProject.instance().mapLayers(True).values()) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) self.assertEqual(QgsProject.instance().validCount(), 0) self.assertEqual(len(QgsProject.instance().mapLayers(True)), 0) QgsProject.instance().removeAllMapLayers() def test_addMapLayerSignals(self): """ test that signals are correctly emitted when adding map layer""" QgsProject.instance().removeAllMapLayers() layer_was_added_spy = QSignalSpy(QgsProject.instance().layerWasAdded) layers_added_spy = QSignalSpy(QgsProject.instance().layersAdded) legend_layers_added_spy = QSignalSpy(QgsProject.instance().legendLayersAdded) l1 = createLayer('test') QgsProject.instance().addMapLayer(l1) # can't seem to actually test the data which was emitted, so best we can do is test # the signal count self.assertEqual(len(layer_was_added_spy), 1) self.assertEqual(len(layers_added_spy), 1) self.assertEqual(len(legend_layers_added_spy), 1) # layer not added to legend QgsProject.instance().addMapLayer(createLayer('test2'), False) self.assertEqual(len(layer_was_added_spy), 2) self.assertEqual(len(layers_added_spy), 2) self.assertEqual(len(legend_layers_added_spy), 1) # try readding a layer already in the registry QgsProject.instance().addMapLayer(l1) # should be no extra signals emitted self.assertEqual(len(layer_was_added_spy), 2) self.assertEqual(len(layers_added_spy), 2) self.assertEqual(len(legend_layers_added_spy), 1) def test_addMapLayers(self): """ test adding multiple map layers to registry """ QgsProject.instance().removeAllMapLayers() l1 = createLayer('test') l2 = createLayer('test2') self.assertEqual(set(QgsProject.instance().addMapLayers([l1, l2])), set([l1, l2])) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test2')), 1) self.assertEqual(QgsProject.instance().count(), 2) # adding more layers should leave existing layers intact l3 = createLayer('test3') l4 = createLayer('test4') self.assertEqual(set(QgsProject.instance().addMapLayers([l3, l4])), set([l3, l4])) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test2')), 1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test3')), 1) self.assertEqual(len(QgsProject.instance().mapLayersByName('test4')), 1) self.assertEqual(QgsProject.instance().count(), 4) QgsProject.instance().removeAllMapLayers() def test_addMapLayersInvalid(self): """ test that invalid map layers can be added to registry """ QgsProject.instance().removeAllMapLayers() vl = QgsVectorLayer("Point?field=x:string", 'test', "xxx") self.assertEqual(QgsProject.instance().addMapLayers([vl]), [vl]) self.assertFalse(vl in QgsProject.instance().mapLayers(True).values()) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) self.assertEqual(QgsProject.instance().validCount(), 0) QgsProject.instance().removeAllMapLayers() def test_addMapLayersAlreadyAdded(self): """ test that already added layers can't be readded to registry """ QgsProject.instance().removeAllMapLayers() l1 = createLayer('test') self.assertEqual(QgsProject.instance().addMapLayers([l1]), [l1]) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) self.assertEqual(QgsProject.instance().addMapLayers([l1]), []) self.assertEqual(len(QgsProject.instance().mapLayersByName('test')), 1) self.assertEqual(QgsProject.instance().count(), 1) QgsProject.instance().removeAllMapLayers() def test_addMapLayersSignals(self): """ test that signals are correctly emitted when adding map layers""" QgsProject.instance().removeAllMapLayers() layer_was_added_spy = QSignalSpy(QgsProject.instance().layerWasAdded) layers_added_spy = QSignalSpy(QgsProject.instance().layersAdded) legend_layers_added_spy = QSignalSpy(QgsProject.instance().legendLayersAdded) l1 = createLayer('test') l2 = createLayer('test2') QgsProject.instance().addMapLayers([l1, l2]) # can't seem to actually test the data which was emitted, so best we can do is test # the signal count self.assertEqual(len(layer_was_added_spy), 2) self.assertEqual(len(layers_added_spy), 1) self.assertEqual(len(legend_layers_added_spy), 1) # layer not added to legend QgsProject.instance().addMapLayers([createLayer('test3'), createLayer('test4')], False) self.assertEqual(len(layer_was_added_spy), 4) self.assertEqual(len(layers_added_spy), 2) self.assertEqual(len(legend_layers_added_spy), 1) # try readding a layer already in the registry QgsProject.instance().addMapLayers([l1, l2]) # should be no extra signals emitted self.assertEqual(len(layer_was_added_spy), 4) self.assertEqual(len(layers_added_spy), 2) self.assertEqual(len(legend_layers_added_spy), 1) def test_mapLayerById(self): """ test retrieving map layer by ID """ QgsProject.instance().removeAllMapLayers() # test no crash with empty registry self.assertEqual(QgsProject.instance().mapLayer('bad'), None) self.assertEqual(QgsProject.instance().mapLayer(None), None) l1 = createLayer('test') l2 = createLayer('test2') QgsProject.instance().addMapLayers([l1, l2]) self.assertEqual(QgsProject.instance().mapLayer('bad'), None) self.assertEqual(QgsProject.instance().mapLayer(None), None) self.assertEqual(QgsProject.instance().mapLayer(l1.id()), l1) self.assertEqual(QgsProject.instance().mapLayer(l2.id()), l2) def test_mapLayersByName(self): """ test retrieving map layer by name """ p = QgsProject() # test no crash with empty registry self.assertEqual(p.mapLayersByName('bad'), []) self.assertEqual(p.mapLayersByName(None), []) l1 = createLayer('test') l2 = createLayer('test2') p.addMapLayers([l1, l2]) self.assertEqual(p.mapLayersByName('bad'), []) self.assertEqual(p.mapLayersByName(None), []) self.assertEqual(p.mapLayersByName('test'), [l1]) self.assertEqual(p.mapLayersByName('test2'), [l2]) #duplicate name l3 = createLayer('test') p.addMapLayer(l3) self.assertEqual(set(p.mapLayersByName('test')), set([l1, l3])) def test_mapLayers(self): """ test retrieving map layers list """ QgsProject.instance().removeAllMapLayers() # test no crash with empty registry self.assertEqual(QgsProject.instance().mapLayers(), {}) l1 = createLayer('test') l2 = createLayer('test2') QgsProject.instance().addMapLayers([l1, l2]) self.assertEqual(QgsProject.instance().mapLayers(), {l1.id(): l1, l2.id(): l2}) def test_removeMapLayersById(self): """ test removing map layers by ID """ QgsProject.instance().removeAllMapLayers() # test no crash with empty registry QgsProject.instance().removeMapLayers(['bad']) QgsProject.instance().removeMapLayers([None]) l1 = createLayer('test') l2 = createLayer('test2') l3 = createLayer('test3') QgsProject.instance().addMapLayers([l1, l2, l3]) self.assertEqual(QgsProject.instance().count(), 3) #remove bad layers QgsProject.instance().removeMapLayers(['bad']) self.assertEqual(QgsProject.instance().count(), 3) QgsProject.instance().removeMapLayers([None]) self.assertEqual(QgsProject.instance().count(), 3) # remove valid layers l1_id = l1.id() QgsProject.instance().removeMapLayers([l1_id]) self.assertEqual(QgsProject.instance().count(), 2) # double remove QgsProject.instance().removeMapLayers([l1_id]) self.assertEqual(QgsProject.instance().count(), 2) # test that layer has been deleted self.assertTrue(sip.isdeleted(l1)) # remove multiple QgsProject.instance().removeMapLayers([l2.id(), l3.id()]) self.assertEqual(QgsProject.instance().count(), 0) self.assertTrue(sip.isdeleted(l2)) # try removing a layer not in the registry l4 = createLayer('test4') QgsProject.instance().removeMapLayers([l4.id()]) self.assertFalse(sip.isdeleted(l4)) # fails on qt5 due to removeMapLayers list type conversion - needs a PyName alias # added to removeMapLayers for QGIS 3.0 @unittest.expectedFailure(QT_VERSION_STR[0] == '5') def test_removeMapLayersByLayer(self): """ test removing map layers by layer""" QgsProject.instance().removeAllMapLayers() # test no crash with empty registry QgsProject.instance().removeMapLayers([None]) l1 = createLayer('test') l2 = createLayer('test2') l3 = createLayer('test3') QgsProject.instance().addMapLayers([l1, l2, l3]) self.assertEqual(QgsProject.instance().count(), 3) #remove bad layers QgsProject.instance().removeMapLayers([None]) self.assertEqual(QgsProject.instance().count(), 3) # remove valid layers QgsProject.instance().removeMapLayers([l1]) self.assertEqual(QgsProject.instance().count(), 2) # test that layer has been deleted self.assertTrue(sip.isdeleted(l1)) # remove multiple QgsProject.instance().removeMapLayers([l2, l3]) self.assertEqual(QgsProject.instance().count(), 0) self.assertTrue(sip.isdeleted(l2)) self.assertTrue(sip.isdeleted(l3)) def test_removeMapLayerById(self): """ test removing a map layer by ID """ QgsProject.instance().removeAllMapLayers() # test no crash with empty registry QgsProject.instance().removeMapLayer('bad') QgsProject.instance().removeMapLayer(None) l1 = createLayer('test') l2 = createLayer('test2') QgsProject.instance().addMapLayers([l1, l2]) self.assertEqual(QgsProject.instance().count(), 2) #remove bad layers QgsProject.instance().removeMapLayer('bad') self.assertEqual(QgsProject.instance().count(), 2) QgsProject.instance().removeMapLayer(None) self.assertEqual(QgsProject.instance().count(), 2) # remove valid layers l1_id = l1.id() QgsProject.instance().removeMapLayer(l1_id) self.assertEqual(QgsProject.instance().count(), 1) # double remove QgsProject.instance().removeMapLayer(l1_id) self.assertEqual(QgsProject.instance().count(), 1) # test that layer has been deleted self.assertTrue(sip.isdeleted(l1)) # remove second layer QgsProject.instance().removeMapLayer(l2.id()) self.assertEqual(QgsProject.instance().count(), 0) self.assertTrue(sip.isdeleted(l2)) # try removing a layer not in the registry l3 = createLayer('test3') QgsProject.instance().removeMapLayer(l3.id()) self.assertFalse(sip.isdeleted(l3)) def test_removeMapLayerByLayer(self): """ test removing a map layer by layer """ QgsProject.instance().removeAllMapLayers() # test no crash with empty registry QgsProject.instance().removeMapLayer('bad') QgsProject.instance().removeMapLayer(None) l1 = createLayer('test') l2 = createLayer('test2') QgsProject.instance().addMapLayers([l1, l2]) self.assertEqual(QgsProject.instance().count(), 2) #remove bad layers QgsProject.instance().removeMapLayer(None) self.assertEqual(QgsProject.instance().count(), 2) l3 = createLayer('test3') QgsProject.instance().removeMapLayer(l3) self.assertEqual(QgsProject.instance().count(), 2) # remove valid layers QgsProject.instance().removeMapLayer(l1) self.assertEqual(QgsProject.instance().count(), 1) # test that layer has been deleted self.assertTrue(sip.isdeleted(l1)) # remove second layer QgsProject.instance().removeMapLayer(l2) self.assertEqual(QgsProject.instance().count(), 0) self.assertTrue(sip.isdeleted(l2)) # try removing a layer not in the registry l3 = createLayer('test3') QgsProject.instance().removeMapLayer(l3) self.assertFalse(sip.isdeleted(l3)) def test_removeAllMapLayers(self): """ test removing all map layers from registry """ QgsProject.instance().removeAllMapLayers() l1 = createLayer('test') l2 = createLayer('test2') QgsProject.instance().addMapLayers([l1, l2]) self.assertEqual(QgsProject.instance().count(), 2) QgsProject.instance().removeAllMapLayers() self.assertEqual(QgsProject.instance().count(), 0) self.assertEqual(QgsProject.instance().mapLayersByName('test'), []) self.assertEqual(QgsProject.instance().mapLayersByName('test2'), []) def test_addRemoveLayersSignals(self): """ test that signals are correctly emitted when removing map layers""" QgsProject.instance().removeAllMapLayers() layers_will_be_removed_spy = QSignalSpy(QgsProject.instance().layersWillBeRemoved) layer_will_be_removed_spy_str = QSignalSpy(QgsProject.instance().layerWillBeRemoved[str]) layer_will_be_removed_spy_layer = QSignalSpy(QgsProject.instance().layerWillBeRemoved[QgsMapLayer]) layers_removed_spy = QSignalSpy(QgsProject.instance().layersRemoved) layer_removed_spy = QSignalSpy(QgsProject.instance().layerRemoved) remove_all_spy = QSignalSpy(QgsProject.instance().removeAll) l1 = createLayer('l1') l2 = createLayer('l2') l3 = createLayer('l3') l4 = createLayer('l4') QgsProject.instance().addMapLayers([l1, l2, l3, l4]) # remove 1 layer QgsProject.instance().removeMapLayer(l1) # can't seem to actually test the data which was emitted, so best we can do is test # the signal count self.assertEqual(len(layers_will_be_removed_spy), 1) self.assertEqual(len(layer_will_be_removed_spy_str), 1) self.assertEqual(len(layer_will_be_removed_spy_layer), 1) self.assertEqual(len(layers_removed_spy), 1) self.assertEqual(len(layer_removed_spy), 1) self.assertEqual(len(remove_all_spy), 0) self.assertEqual(QgsProject.instance().count(), 3) # remove 2 layers at once QgsProject.instance().removeMapLayers([l2.id(), l3.id()]) self.assertEqual(len(layers_will_be_removed_spy), 2) self.assertEqual(len(layer_will_be_removed_spy_str), 3) self.assertEqual(len(layer_will_be_removed_spy_layer), 3) self.assertEqual(len(layers_removed_spy), 2) self.assertEqual(len(layer_removed_spy), 3) self.assertEqual(len(remove_all_spy), 0) self.assertEqual(QgsProject.instance().count(), 1) # remove all QgsProject.instance().removeAllMapLayers() self.assertEqual(len(layers_will_be_removed_spy), 3) self.assertEqual(len(layer_will_be_removed_spy_str), 4) self.assertEqual(len(layer_will_be_removed_spy_layer), 4) self.assertEqual(len(layers_removed_spy), 3) self.assertEqual(len(layer_removed_spy), 4) self.assertEqual(len(remove_all_spy), 1) #remove some layers which aren't in the registry QgsProject.instance().removeMapLayers(['asdasd']) self.assertEqual(len(layers_will_be_removed_spy), 3) self.assertEqual(len(layer_will_be_removed_spy_str), 4) self.assertEqual(len(layer_will_be_removed_spy_layer), 4) self.assertEqual(len(layers_removed_spy), 3) self.assertEqual(len(layer_removed_spy), 4) self.assertEqual(len(remove_all_spy), 1) l5 = createLayer('test5') QgsProject.instance().removeMapLayer(l5) self.assertEqual(len(layers_will_be_removed_spy), 3) self.assertEqual(len(layer_will_be_removed_spy_str), 4) self.assertEqual(len(layer_will_be_removed_spy_layer), 4) self.assertEqual(len(layers_removed_spy), 3) self.assertEqual(len(layer_removed_spy), 4) self.assertEqual(len(remove_all_spy), 1) def test_RemoveLayerShouldNotSegFault(self): QgsProject.instance().removeAllMapLayers() reg = QgsProject.instance() # Should not segfault reg.removeMapLayers(['not_exists']) reg.removeMapLayer('not_exists2') # check also that the removal of an unexistent layer does not insert a null layer for k, layer in list(reg.mapLayers().items()): assert(layer is not None) def testTakeLayer(self): # test taking ownership of a layer from the project l1 = createLayer('l1') l2 = createLayer('l2') p = QgsProject() # add one layer to project p.addMapLayer(l1) self.assertEqual(p.mapLayers(), {l1.id(): l1}) self.assertEqual(l1.parent().parent(), p) # try taking some layers which don't exist in project self.assertFalse(p.takeMapLayer(None)) self.assertFalse(p.takeMapLayer(l2)) # but l2 should still exist.. self.assertTrue(l2.isValid()) # take layer from project self.assertEqual(p.takeMapLayer(l1), l1) self.assertFalse(p.mapLayers()) # no layers left # but l1 should still exist self.assertTrue(l1.isValid()) # layer should have no parent now self.assertFalse(l1.parent()) # destroy project p = None self.assertTrue(l1.isValid()) def test_transactionsGroup(self): # Undefined transaction group (wrong provider key). QgsProject.instance().setAutoTransaction(True) noTg = QgsProject.instance().transactionGroup("provider-key", "database-connection-string") self.assertIsNone(noTg) def test_zip_new_project(self): tmpDir = QTemporaryDir() tmpFile = "{}/project.qgz".format(tmpDir.path()) # zip with existing file open(tmpFile, 'a').close() project = QgsProject() self.assertTrue(project.write(tmpFile)) # zip with non existing file os.remove(tmpFile) project = QgsProject() self.assertTrue(project.write(tmpFile)) self.assertTrue(os.path.isfile(tmpFile)) def test_zip_invalid_path(self): project = QgsProject() self.assertFalse(project.write()) self.assertFalse(project.write("")) self.assertFalse(project.write("/fake/test.zip")) def test_zip_filename(self): tmpDir = QTemporaryDir() tmpFile = "{}/project.qgz".format(tmpDir.path()) project = QgsProject() self.assertFalse(project.write()) project.setFileName(tmpFile) self.assertTrue(project.write()) self.assertTrue(os.path.isfile(tmpFile)) def test_unzip_invalid_path(self): project = QgsProject() self.assertFalse(project.read()) self.assertFalse(project.read("")) self.assertFalse(project.read("/fake/test.zip")) def test_zip_unzip(self): tmpDir = QTemporaryDir() tmpFile = "{}/project.qgz".format(tmpDir.path()) project = QgsProject() l0 = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "points.shp"), "points", "ogr") l1 = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "lines.shp"), "lines", "ogr") project.addMapLayers([l0, l1]) self.assertTrue(project.write(tmpFile)) project2 = QgsProject() self.assertFalse(project2.isZipped()) self.assertTrue(project2.fileName() == "") self.assertTrue(project2.read(tmpFile)) self.assertTrue(project2.isZipped()) self.assertTrue(project2.fileName() == tmpFile) layers = project2.mapLayers() self.assertEqual(len(layers.keys()), 2) self.assertTrue(layers[l0.id()].isValid(), True) self.assertTrue(layers[l1.id()].isValid(), True) project2.clear() self.assertFalse(project2.isZipped()) def testUpgradeOtfFrom2x(self): """ Test that upgrading a 2.x project correctly brings across project CRS and OTF transformation settings """ prj = QgsProject.instance() prj.read(os.path.join(TEST_DATA_DIR, 'projects', 'test_memory_layer_proj.qgs')) self.assertTrue(prj.crs().isValid()) self.assertEqual(prj.crs().authid(), 'EPSG:2056') def testRelativePaths(self): """ Test whether paths to layer sources are stored as relative to the project path """ tmpDir = QTemporaryDir() tmpFile = "{}/project.qgs".format(tmpDir.path()) copyfile(os.path.join(TEST_DATA_DIR, "points.shp"), os.path.join(tmpDir.path(), "points.shp")) copyfile(os.path.join(TEST_DATA_DIR, "points.dbf"), os.path.join(tmpDir.path(), "points.dbf")) copyfile(os.path.join(TEST_DATA_DIR, "points.shx"), os.path.join(tmpDir.path(), "points.shx")) copyfile(os.path.join(TEST_DATA_DIR, "lines.shp"), os.path.join(tmpDir.path(), "lines.shp")) copyfile(os.path.join(TEST_DATA_DIR, "lines.dbf"), os.path.join(tmpDir.path(), "lines.dbf")) copyfile(os.path.join(TEST_DATA_DIR, "lines.shx"), os.path.join(tmpDir.path(), "lines.shx")) copyfile(os.path.join(TEST_DATA_DIR, "landsat_4326.tif"), os.path.join(tmpDir.path(), "landsat_4326.tif")) project = QgsProject() l0 = QgsVectorLayer(os.path.join(tmpDir.path(), "points.shp"), "points", "ogr") l1 = QgsVectorLayer(os.path.join(tmpDir.path(), "lines.shp"), "lines", "ogr") l2 = QgsRasterLayer(os.path.join(tmpDir.path(), "landsat_4326.tif"), "landsat", "gdal") self.assertTrue(l0.isValid()) self.assertTrue(l1.isValid()) self.assertTrue(l2.isValid()) self.assertTrue(project.addMapLayers([l0, l1, l2])) self.assertTrue(project.write(tmpFile)) del project with open(tmpFile, 'r') as f: content = ''.join(f.readlines()) self.assertTrue('source="./lines.shp"' in content) self.assertTrue('source="./points.shp"' in content) self.assertTrue('source="./landsat_4326.tif"' in content) # Re-read the project and store absolute project = QgsProject() self.assertTrue(project.read(tmpFile)) store = project.layerStore() self.assertEquals(set([l.name() for l in store.mapLayers().values()]), set(['lines', 'landsat', 'points'])) project.writeEntryBool('Paths', '/Absolute', True) tmpFile2 = "{}/project2.qgs".format(tmpDir.path()) self.assertTrue(project.write(tmpFile2)) with open(tmpFile2, 'r') as f: content = ''.join(f.readlines()) self.assertTrue('source="{}/lines.shp"'.format(tmpDir.path()) in content) self.assertTrue('source="{}/points.shp"'.format(tmpDir.path()) in content) self.assertTrue('source="{}/landsat_4326.tif"'.format(tmpDir.path()) in content) del project def testSymbolicLinkInProjectPath(self): """ Test whether paths to layer sources relative to the project are stored correctly when project'name contains a symbolic link. In other words, test if project's and layers' names are correctly resolved. """ tmpDir = QTemporaryDir() tmpFile = "{}/project.qgs".format(tmpDir.path()) copyfile(os.path.join(TEST_DATA_DIR, "points.shp"), os.path.join(tmpDir.path(), "points.shp")) copyfile(os.path.join(TEST_DATA_DIR, "points.dbf"), os.path.join(tmpDir.path(), "points.dbf")) copyfile(os.path.join(TEST_DATA_DIR, "points.shx"), os.path.join(tmpDir.path(), "points.shx")) copyfile(os.path.join(TEST_DATA_DIR, "lines.shp"), os.path.join(tmpDir.path(), "lines.shp")) copyfile(os.path.join(TEST_DATA_DIR, "lines.dbf"), os.path.join(tmpDir.path(), "lines.dbf")) copyfile(os.path.join(TEST_DATA_DIR, "lines.shx"), os.path.join(tmpDir.path(), "lines.shx")) copyfile(os.path.join(TEST_DATA_DIR, "landsat_4326.tif"), os.path.join(tmpDir.path(), "landsat_4326.tif")) project = QgsProject() l0 = QgsVectorLayer(os.path.join(tmpDir.path(), "points.shp"), "points", "ogr") l1 = QgsVectorLayer(os.path.join(tmpDir.path(), "lines.shp"), "lines", "ogr") l2 = QgsRasterLayer(os.path.join(tmpDir.path(), "landsat_4326.tif"), "landsat", "gdal") self.assertTrue(l0.isValid()) self.assertTrue(l1.isValid()) self.assertTrue(l2.isValid()) self.assertTrue(project.addMapLayers([l0, l1, l2])) self.assertTrue(project.write(tmpFile)) del project # Create symbolic link to previous project tmpDir2 = QTemporaryDir() symlinkDir = os.path.join(tmpDir2.path(), "dir") os.symlink(tmpDir.path(), symlinkDir) tmpFile = "{}/project.qgs".format(symlinkDir) # Open project from symmlink and force re-save. project = QgsProject() self.assertTrue(project.read(tmpFile)) self.assertTrue(project.write(tmpFile)) del project with open(tmpFile, 'r') as f: content = ''.join(f.readlines()) self.assertTrue('source="./lines.shp"' in content) self.assertTrue('source="./points.shp"' in content) self.assertTrue('source="./landsat_4326.tif"' in content) def testHomePath(self): p = QgsProject() path_changed_spy = QSignalSpy(p.homePathChanged) self.assertFalse(p.homePath()) self.assertFalse(p.presetHomePath()) # simulate save file tmp_dir = QTemporaryDir() tmp_file = "{}/project.qgs".format(tmp_dir.path()) with open(tmp_file, 'w') as f: pass p.setFileName(tmp_file) # home path should be file path self.assertEqual(p.homePath(), tmp_dir.path()) self.assertFalse(p.presetHomePath()) self.assertEqual(len(path_changed_spy), 1) # manually override home path p.setPresetHomePath('/tmp/my_path') self.assertEqual(p.homePath(), '/tmp/my_path') self.assertEqual(p.presetHomePath(), '/tmp/my_path') self.assertEqual(len(path_changed_spy), 2) # check project scope scope = QgsExpressionContextUtils.projectScope(p) self.assertEqual(scope.variable('project_home'), '/tmp/my_path') # no extra signal if path is unchanged p.setPresetHomePath('/tmp/my_path') self.assertEqual(p.homePath(), '/tmp/my_path') self.assertEqual(p.presetHomePath(), '/tmp/my_path') self.assertEqual(len(path_changed_spy), 2) # setting file name should not affect home path is manually set tmp_file_2 = "{}/project/project2.qgs".format(tmp_dir.path()) os.mkdir(tmp_dir.path() + '/project') with open(tmp_file_2, 'w') as f: pass p.setFileName(tmp_file_2) self.assertEqual(p.homePath(), '/tmp/my_path') self.assertEqual(p.presetHomePath(), '/tmp/my_path') self.assertEqual(len(path_changed_spy), 2) scope = QgsExpressionContextUtils.projectScope(p) self.assertEqual(scope.variable('project_home'), '/tmp/my_path') # clear manual path p.setPresetHomePath('') self.assertEqual(p.homePath(), tmp_dir.path() + '/project') self.assertFalse(p.presetHomePath()) self.assertEqual(len(path_changed_spy), 3) scope = QgsExpressionContextUtils.projectScope(p) self.assertEqual(scope.variable('project_home'), tmp_dir.path() + '/project') # relative path p.setPresetHomePath('../home') self.assertEqual(p.homePath(), tmp_dir.path() + '/home') self.assertEqual(p.presetHomePath(), '../home') self.assertEqual(len(path_changed_spy), 4) scope = QgsExpressionContextUtils.projectScope(p) self.assertEqual(scope.variable('project_home'), tmp_dir.path() + '/home') # relative path, no filename p.setFileName('') self.assertEqual(p.homePath(), '../home') self.assertEqual(p.presetHomePath(), '../home') scope = QgsExpressionContextUtils.projectScope(p) self.assertEqual(scope.variable('project_home'), '../home') def testDirtyBlocker(self): # first test manual QgsProjectDirtyBlocker construction p = QgsProject() dirty_spy = QSignalSpy(p.isDirtyChanged) # ^ will do *whatever* it takes to discover the enemy's secret plans! # simple checks p.setDirty(True) self.assertTrue(p.isDirty()) self.assertEqual(len(dirty_spy), 1) self.assertEqual(dirty_spy[-1], [True]) p.setDirty(True) # already dirty self.assertTrue(p.isDirty()) self.assertEqual(len(dirty_spy), 1) p.setDirty(False) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 2) self.assertEqual(dirty_spy[-1], [False]) p.setDirty(True) self.assertTrue(p.isDirty()) self.assertEqual(len(dirty_spy), 3) self.assertEqual(dirty_spy[-1], [True]) # with a blocker blocker = QgsProjectDirtyBlocker(p) # blockers will allow cleaning projects p.setDirty(False) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 4) self.assertEqual(dirty_spy[-1], [False]) # but not dirtying! p.setDirty(True) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 4) self.assertEqual(dirty_spy[-1], [False]) # nested block blocker2 = QgsProjectDirtyBlocker(p) p.setDirty(True) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 4) self.assertEqual(dirty_spy[-1], [False]) del blocker2 p.setDirty(True) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 4) self.assertEqual(dirty_spy[-1], [False]) del blocker p.setDirty(True) self.assertTrue(p.isDirty()) self.assertEqual(len(dirty_spy), 5) self.assertEqual(dirty_spy[-1], [True]) # using python context manager with QgsProject.blockDirtying(p): # cleaning allowed p.setDirty(False) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 6) self.assertEqual(dirty_spy[-1], [False]) # but not dirtying! p.setDirty(True) self.assertFalse(p.isDirty()) self.assertEqual(len(dirty_spy), 6) self.assertEqual(dirty_spy[-1], [False]) # unblocked p.setDirty(True) self.assertTrue(p.isDirty()) self.assertEqual(len(dirty_spy), 7) self.assertEqual(dirty_spy[-1], [True]) def testCustomLayerOrderFrom2xProject(self): prj = QgsProject.instance() prj.read(os.path.join(TEST_DATA_DIR, 'layer_rendering_order_issue_qgis3.qgs')) layer_x = prj.mapLayers()['x20180406151213536'] layer_y = prj.mapLayers()['y20180406151217017'] # check layer order tree = prj.layerTreeRoot() self.assertEqual(tree.children()[0].layer(), layer_x) self.assertEqual(tree.children()[1].layer(), layer_y) self.assertTrue(tree.hasCustomLayerOrder()) self.assertEqual(tree.customLayerOrder(), [layer_y, layer_x]) self.assertEqual(tree.layerOrder(), [layer_y, layer_x]) def testCustomLayerOrderFrom3xProject(self): prj = QgsProject.instance() prj.read(os.path.join(TEST_DATA_DIR, 'layer_rendering_order_qgis3_project.qgs')) layer_x = prj.mapLayers()['x20180406151213536'] layer_y = prj.mapLayers()['y20180406151217017'] # check layer order tree = prj.layerTreeRoot() self.assertEqual(tree.children()[0].layer(), layer_x) self.assertEqual(tree.children()[1].layer(), layer_y) self.assertTrue(tree.hasCustomLayerOrder()) self.assertEqual(tree.customLayerOrder(), [layer_y, layer_x]) self.assertEqual(tree.layerOrder(), [layer_y, layer_x]) def testPalPropertiesReadWrite(self): tmpDir = QTemporaryDir() tmpFile = "{}/project.qgs".format(tmpDir.path()) s0 = QgsLabelingEngineSettings() s0.setNumCandidatePositions(3, 33, 333) p0 = QgsProject() p0.setFileName(tmpFile) p0.setLabelingEngineSettings(s0) p0.write() p1 = QgsProject() p1.read(tmpFile) s1 = p1.labelingEngineSettings() candidates = s1.numCandidatePositions() self.assertEqual(candidates[0], 3) self.assertEqual(candidates[1], 33) self.assertEqual(candidates[2], 333) def testLayerChangeDirtiesProject(self): """ Test that making changes to certain layer properties results in dirty projects """ p = QgsProject() l = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "points.shp"), "points", "ogr") self.assertTrue(l.isValid()) self.assertTrue(p.addMapLayers([l])) p.setDirty(False) l.setCrs(QgsCoordinateReferenceSystem('EPSG:3111')) self.assertTrue(p.isDirty()) p.setDirty(False) l.setName('test') self.assertTrue(p.isDirty()) p.setDirty(False) self.assertTrue(l.setSubsetString('class=\'a\'')) self.assertTrue(p.isDirty()) def testProjectTitleWithPeriod(self): tmpDir = QTemporaryDir() tmpFile = "{}/2.18.21.qgs".format(tmpDir.path()) tmpFile2 = "{}/qgis-3.2.0.qgs".format(tmpDir.path()) p0 = QgsProject() p0.setFileName(tmpFile) p1 = QgsProject() p1.setFileName(tmpFile2) self.assertEqual(p0.baseName(), '2.18.21') self.assertEqual(p1.baseName(), 'qgis-3.2.0') def testWriteEntry(self): tmpDir = QTemporaryDir() tmpFile = "{}/project.qgs".format(tmpDir.path()) # zip with existing file project = QgsProject() query = 'select * from "sample DH" where "sample DH"."Elev" > 130 and "sample DH"."Elev" < 140' self.assertTrue(project.writeEntry('myscope', 'myentry', query)) self.assertTrue(project.write(tmpFile)) self.assertTrue(project.read(tmpFile)) q, ok = project.readEntry('myscope', 'myentry') self.assertTrue(ok) self.assertEqual(q, query) def testDirtying(self): project = QgsProject() # writing a new entry should dirty the project project.setDirty(False) self.assertTrue(project.writeEntry('myscope', 'myentry', True)) self.assertTrue(project.isDirty()) # over-writing a pre-existing entry with the same value should _not_ dirty the project project.setDirty(False) self.assertTrue(project.writeEntry('myscope', 'myentry', True)) self.assertFalse(project.isDirty()) # over-writing a pre-existing entry with a different value should dirty the project project.setDirty(False) self.assertTrue(project.writeEntry('myscope', 'myentry', False)) self.assertTrue(project.isDirty()) # removing an existing entry should dirty the project project.setDirty(False) self.assertTrue(project.removeEntry('myscope', 'myentry')) self.assertTrue(project.isDirty()) # removing a non-existing entry should _not_ dirty the project project.setDirty(False) self.assertTrue(project.removeEntry('myscope', 'myentry')) self.assertFalse(project.isDirty()) # setting a project CRS with a new value should dirty the project project.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) project.setDirty(False) project.setCrs(QgsCoordinateReferenceSystem('EPSG:3148')) self.assertTrue(project.isDirty()) # setting a project CRS with the same project CRS should not dirty the project project.setDirty(False) project.setCrs(QgsCoordinateReferenceSystem('EPSG:3148')) self.assertFalse(project.isDirty()) def testColorScheme(self): p = QgsProject.instance() spy = QSignalSpy(p.projectColorsChanged) p.setProjectColors([[QColor(255, 0, 0), 'red'], [QColor(0, 255, 0), 'green']]) self.assertEqual(len(spy), 1) scheme = [s for s in QgsApplication.colorSchemeRegistry().schemes() if isinstance(s, QgsProjectColorScheme)][0] self.assertEqual([[c[0].name(), c[1]] for c in scheme.fetchColors()], [['#ff0000', 'red'], ['#00ff00', 'green']]) # except color changed signal when clearing project p.clear() self.assertEqual(len(spy), 2) self.assertEqual([[c[0].name(), c[1]] for c in scheme.fetchColors()], []) # should be no signal on project destruction -- can cause a crash p = QgsProject() spy = QSignalSpy(p.projectColorsChanged) p.deleteLater() del p self.assertEqual(len(spy), 0) def testTransformContextSignalIsEmitted(self): """Test that when a project transform context changes a transformContextChanged signal is emitted""" p = QgsProject() spy = QSignalSpy(p.transformContextChanged) ctx = QgsCoordinateTransformContext() ctx.addSourceDestinationDatumTransform(QgsCoordinateReferenceSystem(4326), QgsCoordinateReferenceSystem(3857), 1234, 1235) p.setTransformContext(ctx) self.assertEqual(len(spy), 1) if __name__ == '__main__': unittest.main()
2015fallproject/2015fallcase2
refs/heads/master
static/Brython3.2.0-20150701-214155/Lib/calendar.py
828
"""Calendar printing functions Note when comparing these calendars to the ones printed by cal(1): By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week (0=Monday, 6=Sunday).""" import sys import datetime import locale as _locale __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", "firstweekday", "isleap", "leapdays", "weekday", "monthrange", "monthcalendar", "prmonth", "month", "prcal", "calendar", "timegm", "month_name", "month_abbr", "day_name", "day_abbr"] # Exception raised for bad input (with string parameter for details) error = ValueError # Exceptions raised for bad input class IllegalMonthError(ValueError): def __init__(self, month): self.month = month def __str__(self): return "bad month number %r; must be 1-12" % self.month class IllegalWeekdayError(ValueError): def __init__(self, weekday): self.weekday = weekday def __str__(self): return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday # Constants for months referenced later January = 1 February = 2 # Number of days per month (except for February in leap years) mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This module used to have hard-coded lists of day and month names, as # English strings. The classes following emulate a read-only version of # that, but supply localized names. Note that the values are computed # fresh on each call, in case the user changes locale between calls. class _localized_month: _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)] _months.insert(0, lambda x: "") def __init__(self, format): self.format = format def __getitem__(self, i): funcs = self._months[i] if isinstance(i, slice): return [f(self.format) for f in funcs] else: return funcs(self.format) def __len__(self): return 13 class _localized_day: # January 1, 2001, was a Monday. _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)] def __init__(self, format): self.format = format def __getitem__(self, i): funcs = self._days[i] if isinstance(i, slice): return [f(self.format) for f in funcs] else: return funcs(self.format) def __len__(self): return 7 # Full and abbreviated names of weekdays day_name = _localized_day('%A') day_abbr = _localized_day('%a') # Full and abbreviated names of months (1-based arrays!!!) month_name = _localized_month('%B') month_abbr = _localized_month('%b') # Constants for weekdays (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) def isleap(year): """Return True for leap years, False for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400) def weekday(year, month, day): """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31).""" return datetime.date(year, month, day).weekday() def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise IllegalMonthError(month) day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays class Calendar(object): """ Base calendar class. This class doesn't do any formatting. It simply provides data to subclasses. """ def __init__(self, firstweekday=0): self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday def getfirstweekday(self): return self._firstweekday % 7 def setfirstweekday(self, firstweekday): self._firstweekday = firstweekday firstweekday = property(getfirstweekday, setfirstweekday) def iterweekdays(self): """ Return a iterator for one week of weekday numbers starting with the configured first one. """ for i in range(self.firstweekday, self.firstweekday + 7): yield i%7 def itermonthdates(self, year, month): """ Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ date = datetime.date(year, month, 1) # Go back to the beginning of the week days = (date.weekday() - self.firstweekday) % 7 date -= datetime.timedelta(days=days) oneday = datetime.timedelta(days=1) while True: yield date try: date += oneday except OverflowError: # Adding one day could fail after datetime.MAXYEAR break if date.month != month and date.weekday() == self.firstweekday: break def itermonthdays2(self, year, month): """ Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0. """ for date in self.itermonthdates(year, month): if date.month != month: yield (0, date.weekday()) else: yield (date.day, date.weekday()) def itermonthdays(self, year, month): """ Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0. """ for date in self.itermonthdates(year, month): if date.month != month: yield 0 else: yield date.day def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ] def monthdays2calendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero. """ days = list(self.itermonthdays2(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ] def monthdayscalendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero. """ days = list(self.itermonthdays(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ] def yeardatescalendar(self, year, width=3): """ Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects. """ months = [ self.monthdatescalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ] def yeardays2calendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero. """ months = [ self.monthdays2calendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ] def yeardayscalendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. """ months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ] class TextCalendar(Calendar): """ Subclass of Calendar that outputs a calendar as a simple plain text similar to the UNIX program cal. """ def prweek(self, theweek, width): """ Print a single week (no newline). """ print(self.formatweek(theweek, width), end=' ') def formatday(self, day, weekday, width): """ Returns a formatted day. """ if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days return s.center(width) def formatweek(self, theweek, width): """ Returns a single week in a string (no newline). """ return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) def formatweekday(self, day, width): """ Returns a formatted week day name. """ if width >= 9: names = day_name else: names = day_abbr return names[day][:width].center(width) def formatweekheader(self, width): """ Return a header for a week. """ return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays()) def formatmonthname(self, theyear, themonth, width, withyear=True): """ Return a formatted month name. """ s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear) return s.center(width) def prmonth(self, theyear, themonth, w=0, l=0): """ Print a month's calendar. """ print(self.formatmonth(theyear, themonth, w, l), end=' ') def formatmonth(self, theyear, themonth, w=0, l=0): """ Return a month's calendar string (multi-line). """ w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) s = s.rstrip() s += '\n' * l s += self.formatweekheader(w).rstrip() s += '\n' * l for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += '\n' * l return s def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = range(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip()) a('\n'*l) headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in range(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v) def pryear(self, theyear, w=0, l=0, c=6, m=3): """Print a year's calendar.""" print(self.formatyear(theyear, w, l, c, m)) class HTMLCalendar(Calendar): """ This calendar returns complete HTML pages. """ # CSS classes for the day <td>s cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] def formatday(self, day, weekday): """ Return a day as a table cell. """ if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month else: return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day) def formatweek(self, theweek): """ Return a complete week as a table row. """ s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) return '<tr>%s</tr>' % s def formatweekday(self, day): """ Return a weekday name as a table header. """ return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day]) def formatweekheader(self): """ Return a header for a week as a table row. """ s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) return '<tr>%s</tr>' % s def formatmonthname(self, theyear, themonth, withyear=True): """ Return a month name as a table row. """ if withyear: s = '%s %s' % (month_name[themonth], theyear) else: s = '%s' % month_name[themonth] return '<tr><th colspan="7" class="month">%s</th></tr>' % s def formatmonth(self, theyear, themonth, withyear=True): """ Return a formatted month as a table. """ v = [] a = v.append a('<table border="0" cellpadding="0" cellspacing="0" class="month">') a('\n') a(self.formatmonthname(theyear, themonth, withyear=withyear)) a('\n') a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): a(self.formatweek(week)) a('\n') a('</table>') a('\n') return ''.join(v) def formatyear(self, theyear, width=3): """ Return a formatted year as a table of tables. """ v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="year">') a('\n') a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear)) for i in range(January, January+12, width): # months in this row months = range(i, min(i+width, 13)) a('<tr>') for m in months: a('<td>') a(self.formatmonth(theyear, m, withyear=False)) a('</td>') a('</tr>') a('</table>') return ''.join(v) def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title>\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding, "xmlcharrefreplace") class different_locale: def __init__(self, locale): self.locale = locale def __enter__(self): self.oldlocale = _locale.getlocale(_locale.LC_TIME) _locale.setlocale(_locale.LC_TIME, self.locale) def __exit__(self, *args): _locale.setlocale(_locale.LC_TIME, self.oldlocale) class LocaleTextCalendar(TextCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. """ def __init__(self, firstweekday=0, locale=None): TextCalendar.__init__(self, firstweekday) if locale is None: locale = _locale.getdefaultlocale() self.locale = locale def formatweekday(self, day, width): with different_locale(self.locale): if width >= 9: names = day_name else: names = day_abbr name = names[day] return name[:width].center(width) def formatmonthname(self, theyear, themonth, width, withyear=True): with different_locale(self.locale): s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear) return s.center(width) class LocaleHTMLCalendar(HTMLCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. """ def __init__(self, firstweekday=0, locale=None): HTMLCalendar.__init__(self, firstweekday) if locale is None: locale = _locale.getdefaultlocale() self.locale = locale def formatweekday(self, day): with different_locale(self.locale): s = day_abbr[day] return '<th class="%s">%s</th>' % (self.cssclasses[day], s) def formatmonthname(self, theyear, themonth, withyear=True): with different_locale(self.locale): s = month_name[themonth] if withyear: s = '%s %s' % (s, theyear) return '<tr><th colspan="7" class="month">%s</th></tr>' % s # Support for old module level interface c = TextCalendar() firstweekday = c.getfirstweekday def setfirstweekday(firstweekday): if not MONDAY <= firstweekday <= SUNDAY: raise IllegalWeekdayError(firstweekday) c.firstweekday = firstweekday monthcalendar = c.monthdayscalendar prweek = c.prweek week = c.formatweek weekheader = c.formatweekheader prmonth = c.prmonth month = c.formatmonth calendar = c.formatyear prcal = c.pryear # Spacing of month columns for multi-column year calendar _colwidth = 7*3 - 1 # Amount printed by prweek() _spacing = 6 # Number of spaces between columns def format(cols, colwidth=_colwidth, spacing=_spacing): """Prints multi-column formatting for year calendars""" print(formatstring(cols, colwidth, spacing)) def formatstring(cols, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from n strings, centered within n columns.""" spacing *= ' ' return spacing.join(c.center(colwidth) for c in cols) EPOCH = 1970 _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal() def timegm(tuple): """Unrelated but handy function to calculate Unix timestamp from GMT.""" year, month, day, hour, minute, second = tuple[:6] days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]") parser.add_option( "-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)" ) parser.add_option( "-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)" ) parser.add_option( "-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)" ) parser.add_option( "-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)" ) parser.add_option( "-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)" ) parser.add_option( "-L", "--locale", dest="locale", default=None, help="locale to be used from month and weekday names" ) parser.add_option( "-e", "--encoding", dest="encoding", default=None, help="Encoding to use for output." ) parser.add_option( "-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)" ) (options, args) = parser.parse_args(args) if options.locale and not options.encoding: parser.error("if --locale is specified --encoding is required") sys.exit(1) locale = options.locale, options.encoding if options.type == "html": if options.locale: cal = LocaleHTMLCalendar(locale=locale) else: cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) write = sys.stdout.buffer.write if len(args) == 1: write(cal.formatyearpage(datetime.date.today().year, **optdict)) elif len(args) == 2: write(cal.formatyearpage(int(args[1]), **optdict)) else: parser.error("incorrect number of arguments") sys.exit(1) else: if options.locale: cal = LocaleTextCalendar(locale=locale) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: result = cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: result = cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: result = cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) write = sys.stdout.write if options.encoding: result = result.encode(options.encoding) write = sys.stdout.buffer.write write(result) if __name__ == "__main__": main(sys.argv)
sigma-random/asuswrt-merlin
refs/heads/master
release/src/router/samba36/lib/testtools/testtools/runtest.py
20
# Copyright (c) 2009-2010 Jonathan M. Lange. See LICENSE for details. """Individual test case execution.""" __all__ = [ 'MultipleExceptions', 'RunTest', ] import sys from testtools.testresult import ExtendedToOriginalDecorator class MultipleExceptions(Exception): """Represents many exceptions raised from some operation. :ivar args: The sys.exc_info() tuples for each exception. """ class RunTest(object): """An object to run a test. RunTest objects are used to implement the internal logic involved in running a test. TestCase.__init__ stores _RunTest as the class of RunTest to execute. Passing the runTest= parameter to TestCase.__init__ allows a different RunTest class to be used to execute the test. Subclassing or replacing RunTest can be useful to add functionality to the way that tests are run in a given project. :ivar case: The test case that is to be run. :ivar result: The result object a case is reporting to. :ivar handlers: A list of (ExceptionClass, handler_function) for exceptions that should be caught if raised from the user code. Exceptions that are caught are checked against this list in first to last order. There is a catch-all of `Exception` at the end of the list, so to add a new exception to the list, insert it at the front (which ensures that it will be checked before any existing base classes in the list. If you add multiple exceptions some of which are subclasses of each other, add the most specific exceptions last (so they come before their parent classes in the list). :ivar exception_caught: An object returned when _run_user catches an exception. :ivar _exceptions: A list of caught exceptions, used to do the single reporting of error/failure/skip etc. """ def __init__(self, case, handlers=None): """Create a RunTest to run a case. :param case: A testtools.TestCase test case object. :param handlers: Exception handlers for this RunTest. These are stored in self.handlers and can be modified later if needed. """ self.case = case self.handlers = handlers or [] self.exception_caught = object() self._exceptions = [] def run(self, result=None): """Run self.case reporting activity to result. :param result: Optional testtools.TestResult to report activity to. :return: The result object the test was run against. """ if result is None: actual_result = self.case.defaultTestResult() actual_result.startTestRun() else: actual_result = result try: return self._run_one(actual_result) finally: if result is None: actual_result.stopTestRun() def _run_one(self, result): """Run one test reporting to result. :param result: A testtools.TestResult to report activity to. This result object is decorated with an ExtendedToOriginalDecorator to ensure that the latest TestResult API can be used with confidence by client code. :return: The result object the test was run against. """ return self._run_prepared_result(ExtendedToOriginalDecorator(result)) def _run_prepared_result(self, result): """Run one test reporting to result. :param result: A testtools.TestResult to report activity to. :return: The result object the test was run against. """ result.startTest(self.case) self.result = result try: self._exceptions = [] self._run_core() if self._exceptions: # One or more caught exceptions, now trigger the test's # reporting method for just one. e = self._exceptions.pop() for exc_class, handler in self.handlers: if isinstance(e, exc_class): handler(self.case, self.result, e) break finally: result.stopTest(self.case) return result def _run_core(self): """Run the user supplied test code.""" if self.exception_caught == self._run_user(self.case._run_setup, self.result): # Don't run the test method if we failed getting here. self._run_cleanups(self.result) return # Run everything from here on in. If any of the methods raise an # exception we'll have failed. failed = False try: if self.exception_caught == self._run_user( self.case._run_test_method, self.result): failed = True finally: try: if self.exception_caught == self._run_user( self.case._run_teardown, self.result): failed = True finally: try: if self.exception_caught == self._run_user( self._run_cleanups, self.result): failed = True finally: if not failed: self.result.addSuccess(self.case, details=self.case.getDetails()) def _run_cleanups(self, result): """Run the cleanups that have been added with addCleanup. See the docstring for addCleanup for more information. :return: None if all cleanups ran without error, `self.exception_caught` if there was an error. """ failing = False while self.case._cleanups: function, arguments, keywordArguments = self.case._cleanups.pop() got_exception = self._run_user( function, *arguments, **keywordArguments) if got_exception == self.exception_caught: failing = True if failing: return self.exception_caught def _run_user(self, fn, *args, **kwargs): """Run a user supplied function. Exceptions are processed by `_got_user_exception`. :return: Either whatever 'fn' returns or `self.exception_caught` if 'fn' raised an exception. """ try: return fn(*args, **kwargs) except KeyboardInterrupt: raise except: return self._got_user_exception(sys.exc_info()) def _got_user_exception(self, exc_info, tb_label='traceback'): """Called when user code raises an exception. If 'exc_info' is a `MultipleExceptions`, then we recurse into it unpacking the errors that it's made up from. :param exc_info: A sys.exc_info() tuple for the user error. :param tb_label: An optional string label for the error. If not specified, will default to 'traceback'. :return: `exception_caught` if we catch one of the exceptions that have handlers in `self.handlers`, otherwise raise the error. """ if exc_info[0] is MultipleExceptions: for sub_exc_info in exc_info[1].args: self._got_user_exception(sub_exc_info, tb_label) return self.exception_caught try: e = exc_info[1] self.case.onException(exc_info, tb_label=tb_label) finally: del exc_info for exc_class, handler in self.handlers: if isinstance(e, exc_class): self._exceptions.append(e) return self.exception_caught raise e
chauhanhardik/populo_2
refs/heads/master
lms/djangoapps/instructor/management/tests/test_openended_commands.py
106
"""Test the openended_post management command.""" from datetime import datetime import json from mock import patch from pytz import UTC from django.conf import settings from opaque_keys.edx.locations import Location import capa.xqueue_interface as xqueue_interface from courseware.courses import get_course_with_access from courseware.tests.factories import StudentModuleFactory, UserFactory from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.xml_importer import import_course_from_xml from xmodule.open_ended_grading_classes.openendedchild import OpenEndedChild from xmodule.tests.test_util_open_ended import ( STATE_INITIAL, STATE_ACCESSING, STATE_POST_ASSESSMENT ) from student.models import anonymous_id_for_user from instructor.management.commands.openended_post import post_submission_for_student from instructor.management.commands.openended_stats import calculate_task_statistics from instructor.utils import get_module_for_student TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT class OpenEndedPostTest(ModuleStoreTestCase): """Test the openended_post management command.""" def setUp(self): super(OpenEndedPostTest, self).setUp() self.user = UserFactory() store = modulestore() course_items = import_course_from_xml(store, self.user.id, TEST_DATA_DIR, ['open_ended']) # pylint: disable=maybe-no-member self.course = course_items[0] self.course_id = self.course.id self.problem_location = Location("edX", "open_ended", "2012_Fall", "combinedopenended", "SampleQuestion") self.self_assessment_task_number = 0 self.open_ended_task_number = 1 self.student_on_initial = UserFactory() self.student_on_accessing = UserFactory() self.student_on_post_assessment = UserFactory() StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_initial, grade=0, max_grade=1, state=STATE_INITIAL ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_accessing, grade=0, max_grade=1, state=STATE_ACCESSING ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_post_assessment, grade=0, max_grade=1, state=STATE_POST_ASSESSMENT ) def test_post_submission_for_student_on_initial(self): course = get_course_with_access(self.student_on_initial, 'load', self.course_id) dry_run_result = post_submission_for_student(self.student_on_initial, course, self.problem_location, self.open_ended_task_number, dry_run=True) self.assertFalse(dry_run_result) result = post_submission_for_student(self.student_on_initial, course, self.problem_location, self.open_ended_task_number, dry_run=False) self.assertFalse(result) def test_post_submission_for_student_on_accessing(self): course = get_course_with_access(self.student_on_accessing, 'load', self.course_id) dry_run_result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=True) self.assertFalse(dry_run_result) with patch('capa.xqueue_interface.XQueueInterface.send_to_queue') as mock_send_to_queue: mock_send_to_queue.return_value = (0, "Successfully queued") module = get_module_for_student(self.student_on_accessing, self.problem_location) module.child_module.get_task_number(self.open_ended_task_number) student_response = "Here is an answer." student_anonymous_id = anonymous_id_for_user(self.student_on_accessing, None) submission_time = datetime.strftime(datetime.now(UTC), xqueue_interface.dateformat) result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=False) self.assertTrue(result) mock_send_to_queue_body_arg = json.loads(mock_send_to_queue.call_args[1]['body']) self.assertEqual(mock_send_to_queue_body_arg['max_score'], 2) self.assertEqual(mock_send_to_queue_body_arg['student_response'], student_response) body_arg_student_info = json.loads(mock_send_to_queue_body_arg['student_info']) self.assertEqual(body_arg_student_info['anonymous_student_id'], student_anonymous_id) self.assertGreaterEqual(body_arg_student_info['submission_time'], submission_time) def test_post_submission_for_student_on_post_assessment(self): course = get_course_with_access(self.student_on_post_assessment, 'load', self.course_id) dry_run_result = post_submission_for_student(self.student_on_post_assessment, course, self.problem_location, self.open_ended_task_number, dry_run=True) self.assertFalse(dry_run_result) result = post_submission_for_student(self.student_on_post_assessment, course, self.problem_location, self.open_ended_task_number, dry_run=False) self.assertFalse(result) def test_post_submission_for_student_invalid_task(self): course = get_course_with_access(self.student_on_accessing, 'load', self.course_id) result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.self_assessment_task_number, dry_run=False) self.assertFalse(result) out_of_bounds_task_number = 3 result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, out_of_bounds_task_number, dry_run=False) self.assertFalse(result) class OpenEndedStatsTest(ModuleStoreTestCase): """Test the openended_stats management command.""" def setUp(self): super(OpenEndedStatsTest, self).setUp() self.user = UserFactory() store = modulestore() course_items = import_course_from_xml(store, self.user.id, TEST_DATA_DIR, ['open_ended']) # pylint: disable=maybe-no-member self.course = course_items[0] self.course_id = self.course.id self.problem_location = Location("edX", "open_ended", "2012_Fall", "combinedopenended", "SampleQuestion") self.task_number = 1 self.invalid_task_number = 3 self.student_on_initial = UserFactory() self.student_on_accessing = UserFactory() self.student_on_post_assessment = UserFactory() StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_initial, grade=0, max_grade=1, state=STATE_INITIAL ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_accessing, grade=0, max_grade=1, state=STATE_ACCESSING ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_post_assessment, grade=0, max_grade=1, state=STATE_POST_ASSESSMENT ) self.students = [self.student_on_initial, self.student_on_accessing, self.student_on_post_assessment] def test_calculate_task_statistics(self): course = get_course_with_access(self.student_on_accessing, 'load', self.course_id) stats = calculate_task_statistics(self.students, course, self.problem_location, self.task_number, write_to_file=False) self.assertEqual(stats[OpenEndedChild.INITIAL], 1) self.assertEqual(stats[OpenEndedChild.ASSESSING], 1) self.assertEqual(stats[OpenEndedChild.POST_ASSESSMENT], 1) self.assertEqual(stats[OpenEndedChild.DONE], 0) stats = calculate_task_statistics(self.students, course, self.problem_location, self.invalid_task_number, write_to_file=False) self.assertEqual(stats[OpenEndedChild.INITIAL], 0) self.assertEqual(stats[OpenEndedChild.ASSESSING], 0) self.assertEqual(stats[OpenEndedChild.POST_ASSESSMENT], 0) self.assertEqual(stats[OpenEndedChild.DONE], 0)
xsynergy510x/android_external_chromium_org
refs/heads/cm-12.1
tools/cr/cr/loader.py
64
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Module scan and load system. The main interface to this module is the Scan function, which triggers a recursive scan of all packages and modules below cr, with modules being imported as they are found. This allows all the plugins in the system to self register. The aim is to make writing plugins as simple as possible, minimizing the boilerplate so the actual functionality is clearer. """ from importlib import import_module import os import sys import cr # This is the name of the variable inserted into modules to track which # scanners have been applied. _MODULE_SCANNED_TAG = '_CR_MODULE_SCANNED' class AutoExport(object): """A marker for classes that should be promoted up into the cr namespace.""" def _AutoExportScanner(module): """Scan the modules for things that need wiring up automatically.""" for name, value in module.__dict__.items(): if isinstance(value, type) and issubclass(value, AutoExport): # Add this straight to the cr module. if not hasattr(cr, name): setattr(cr, name, value) scan_hooks = [_AutoExportScanner] def _Import(name): """Import a module or package if it is not already imported.""" module = sys.modules.get(name, None) if module is not None: return module return import_module(name, None) def _ScanModule(module): """Runs all the scan_hooks for a module.""" scanner_tags = getattr(module, _MODULE_SCANNED_TAG, None) if scanner_tags is None: # First scan, add the scanned marker set. scanner_tags = set() setattr(module, _MODULE_SCANNED_TAG, scanner_tags) for scan in scan_hooks: if scan not in scanner_tags: scanner_tags.add(scan) scan(module) def _ScanPackage(package): """Scan a package for child packages and modules.""" modules = [] # Recurse sub folders. for path in package.__path__: try: basenames = sorted(os.listdir(path)) except OSError: basenames = [] packages = [] for basename in basenames: fullpath = os.path.join(path, basename) if os.path.isdir(fullpath): name = '.'.join([package.__name__, basename]) packages.append(name) elif basename.endswith('.py') and not basename.startswith('_'): name = '.'.join([package.__name__, basename[:-3]]) module = _Import(name) _ScanModule(module) modules.append(module) for name in packages: child = _Import(name) modules.extend(_ScanPackage(child)) return modules def Import(package, name): module = _Import(package + '.' + name) path = getattr(module, '__path__', None) if path: _ScanPackage(module) else: _ScanModule(module) return module def Scan(): """Scans from the cr package down, loading modules as needed. This finds all packages and modules below the cr package, by scanning the file system. It imports all the packages, and then runs post import hooks on each module to do any automated work. One example of this is the hook that finds all classes that extend AutoExport and copies them up into the cr namespace directly. Modules are allowed to refer to each other, their import will be retried until it succeeds or no progress can be made on any module. """ modules = _ScanPackage(cr) # Now scan all the found modules one more time. # This happens after all imports, in case any imports register scan hooks. for module in modules: _ScanModule(module)
chiefdome/asterisk
refs/heads/master
res/pjproject/tests/pjsua/scripts-media-playrec/100_resample_lf_11_48.py
3
# $Id: 100_resample_lf_11_48.py 369517 2012-07-01 17:28:57Z file $ # from inc_cfg import * # simple test test_param = TestParam( "Resample (large filter) 11 KHZ to 48 KHZ", [ InstanceParam("endpt", "--null-audio --quality 10 --clock-rate 48000 --play-file wavs/input.11.wav --rec-file wavs/tmp.48.wav") ] )
MobinRanjbar/hue
refs/heads/master
desktop/core/ext-py/pycrypto-2.6.1/setup.py
34
#! /usr/bin/env python # # setup.py : Distutils setup script # # Part of the Python Cryptography Toolkit # # =================================================================== # Portions Copyright (c) 2001, 2002, 2003 Python Software Foundation; # All Rights Reserved # # This file contains code from the Python 2.2 setup.py module (the # "Original Code"), with modifications made after it was incorporated # into PyCrypto (the "Modifications"). # # To the best of our knowledge, the Python Software Foundation is the # copyright holder of the Original Code, and has licensed it under the # Python 2.2 license. See the file LEGAL/copy/LICENSE.python-2.2 for # details. # # The Modifications to this file are dedicated to the public domain. # To the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. No rights are # reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== __revision__ = "$Id$" from distutils import core from distutils.ccompiler import new_compiler from distutils.core import Extension, Command from distutils.command.build import build from distutils.command.build_ext import build_ext import os, sys, re import struct if sys.version[0:1] == '1': raise RuntimeError ("The Python Cryptography Toolkit requires " "Python 2.x or 3.x to build.") if sys.platform == 'win32': HTONS_LIBS = ['ws2_32'] plat_ext = [ Extension("Crypto.Random.OSRNG.winrandom", libraries = HTONS_LIBS + ['advapi32'], include_dirs=['src/'], sources=["src/winrand.c"]) ] else: HTONS_LIBS = [] plat_ext = [] # For test development: Set this to 1 to build with gcov support. # Use "gcov -p -o build/temp.*/src build/temp.*/src/*.gcda" to build the # .gcov files USE_GCOV = 0 try: # Python 3 from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2 from distutils.command.build_py import build_py # List of pure Python modules that will be excluded from the binary packages. # The list consists of (package, module_name) tuples if sys.version_info[0] == 2: EXCLUDE_PY = [] else: EXCLUDE_PY = [ # We don't want Py3k to choke on the 2.x compat code ('Crypto.Util', 'py21compat'), ] if sys.platform != "win32": # Avoid nt.py, as 2to3 can't fix it w/o winrandom EXCLUDE_PY += [('Crypto.Random.OSRNG','nt')] # Work around the print / print() issue with Python 2.x and 3.x. We only need # to print at one point of the code, which makes this easy def PrintErr(*args, **kwd): fout = kwd.get("file", sys.stderr) w = fout.write if args: w(str(args[0])) sep = kwd.get("sep", " ") for a in args[1:]: w(sep) w(str(a)) w(kwd.get("end", "\n")) def endianness_macro(): s = struct.pack("@I", 0x33221100) if s == "\x00\x11\x22\x33".encode(): # little endian return ('PCT_LITTLE_ENDIAN', 1) elif s == "\x33\x22\x11\x00".encode(): # big endian return ('PCT_BIG_ENDIAN', 1) raise AssertionError("Machine is neither little-endian nor big-endian") class PCTBuildExt (build_ext): def build_extensions(self): # Detect which modules should be compiled self.detect_modules() # Tweak compiler options if self.compiler.compiler_type in ('unix', 'cygwin', 'mingw32'): # Tell GCC to compile using the C99 standard. self.__add_compiler_option("-std=c99") # ... but don't tell that to the aCC compiler on HP-UX if self.compiler.compiler_so[0] == 'cc' and sys.platform.startswith('hp-ux'): self.__remove_compiler_option("-std=c99") # Make assert() statements always work self.__remove_compiler_option("-DNDEBUG") # Choose our own optimization options for opt in ["-O", "-O0", "-O1", "-O2", "-O3", "-Os"]: self.__remove_compiler_option(opt) if self.debug: # Basic optimization is still needed when debugging to compile # the libtomcrypt code. self.__add_compiler_option("-O") else: # Speed up execution by tweaking compiler options. This # especially helps the DES modules. self.__add_compiler_option("-O3") self.__add_compiler_option("-fomit-frame-pointer") # Don't include debug symbols unless debugging self.__remove_compiler_option("-g") # Don't include profiling information (incompatible with # -fomit-frame-pointer) self.__remove_compiler_option("-pg") if USE_GCOV: self.__add_compiler_option("-fprofile-arcs") self.__add_compiler_option("-ftest-coverage") self.compiler.libraries += ['gcov'] # Call the superclass's build_extensions method build_ext.build_extensions(self) def detect_modules (self): # Read the config.h file (usually generated by autoconf) if self.compiler.compiler_type == 'msvc': # Add special include directory for MSVC (because MSVC is special) self.compiler.include_dirs.insert(0, "src/inc-msvc/") ac = self.__read_autoconf("src/inc-msvc/config.h") else: ac = self.__read_autoconf("src/config.h") # Detect libgmp or libmpir and don't build _fastmath if both are missing. if ac.get("HAVE_LIBGMP"): # Default; no changes needed pass elif ac.get("HAVE_LIBMPIR"): # Change library to libmpir if libgmp is missing self.__change_extension_lib(["Crypto.PublicKey._fastmath"], ['mpir']) # And if this is MSVC, we need to add a linker option # to make a static libmpir link well into a dynamic _fastmath if self.compiler.compiler_type == 'msvc': self.__add_extension_link_option(["Crypto.PublicKey._fastmath"], ["/NODEFAULTLIB:LIBCMT"]) else: # No MP library; use _slowmath. PrintErr ("warning: GMP or MPIR library not found; Not building "+ "Crypto.PublicKey._fastmath.") self.__remove_extensions(["Crypto.PublicKey._fastmath"]) def __add_extension_link_option(self, names, options): """Add linker options for the specified extension(s)""" i = 0 while i < len(self.extensions): if self.extensions[i].name in names: self.extensions[i].extra_link_args = options i += 1 def __change_extension_lib(self, names, libs): """Change the libraries to be used for the specified extension(s)""" i = 0 while i < len(self.extensions): if self.extensions[i].name in names: self.extensions[i].libraries = libs i += 1 def __remove_extensions(self, names): """Remove the specified extension(s) from the list of extensions to build""" i = 0 while i < len(self.extensions): if self.extensions[i].name in names: del self.extensions[i] continue i += 1 def __remove_compiler_option(self, option): """Remove the specified compiler option. Return true if the option was found. Return false otherwise. """ found = 0 for attrname in ('compiler', 'compiler_so'): compiler = getattr(self.compiler, attrname, None) if compiler is not None: while option in compiler: compiler.remove(option) found += 1 return found def __add_compiler_option(self, option): for attrname in ('compiler', 'compiler_so'): compiler = getattr(self.compiler, attrname, None) if compiler is not None: compiler.append(option) def __read_autoconf(self, filename): rx_define = re.compile(r"""^#define (\S+) (?:(\d+)|(".*"))$""") result = {} f = open(filename, "r") try: config_lines = f.read().replace("\r\n", "\n").split("\n") for line in config_lines: m = rx_define.search(line) if not m: continue sym = m.group(1) n = m.group(2) s = m.group(3) if n: result[sym] = int(n) elif s: result[sym] = eval(s) # XXX - hack to unescape C-style string else: continue finally: f.close() return result def run(self): for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) build_ext.run(self) def has_configure(self): compiler = new_compiler(compiler=self.compiler) return compiler.compiler_type != 'msvc' sub_commands = [ ('build_configure', has_configure) ] + build_ext.sub_commands class PCTBuildConfigure(Command): description = "Generate config.h using ./configure (autoconf)" def initialize_options(self): pass def finalize_options(self): pass def run(self): if not os.path.exists("config.status"): if os.system("chmod 0755 configure") != 0: raise RuntimeError("chmod error") cmd = "sh configure" # we use "sh" here so that it'll work on mingw32 with standard python.org binaries if self.verbose < 1: cmd += " -q" if os.system(cmd) != 0: raise RuntimeError("autoconf error") class PCTBuildPy(build_py): def find_package_modules(self, package, package_dir, *args, **kwargs): modules = build_py.find_package_modules(self, package, package_dir, *args, **kwargs) # Exclude certain modules retval = [] for item in modules: pkg, module = item[:2] if (pkg, module) in EXCLUDE_PY: continue retval.append(item) return retval class TestCommand(Command): description = "Run self-test" # Long option name, short option name, description user_options = [ ('skip-slow-tests', None, 'Skip slow tests'), ('module=', 'm', 'Test a single module (e.g. Cipher, PublicKey)') ] def initialize_options(self): self.build_dir = None self.skip_slow_tests = None self.module = None def finalize_options(self): self.set_undefined_options('install', ('build_lib', 'build_dir')) self.config = {'slow_tests': not self.skip_slow_tests} def run(self): # Run SelfTest self.announce("running self-tests") old_path = sys.path[:] try: sys.path.insert(0, self.build_dir) from Crypto import SelfTest moduleObj = None if self.module: if self.module.count('.')==0: # Test a whole a sub-package full_module = "Crypto.SelfTest." + self.module module_name = self.module else: # Test only a module # Assume only one dot is present comps = self.module.split('.') module_name = "test_" + comps[1] full_module = "Crypto.SelfTest." + comps[0] + "." + module_name # Import sub-package or module moduleObj = __import__( full_module, globals(), locals(), module_name ) SelfTest.run(module=moduleObj, verbosity=self.verbose, stream=sys.stdout, config=self.config) finally: # Restore sys.path sys.path[:] = old_path # Run slower self-tests self.announce("running extended self-tests") kw = {'name':"pycrypto", 'version':"2.6.1", # See also: lib/Crypto/__init__.py 'description':"Cryptographic modules for Python.", 'author':"Dwayne C. Litzenberger", 'author_email':"dlitz@dlitz.net", 'url':"http://www.pycrypto.org/", 'cmdclass' : {'build_configure': PCTBuildConfigure, 'build_ext': PCTBuildExt, 'build_py': PCTBuildPy, 'test': TestCommand }, 'packages' : ["Crypto", "Crypto.Hash", "Crypto.Cipher", "Crypto.Util", "Crypto.Random", "Crypto.Random.Fortuna", "Crypto.Random.OSRNG", "Crypto.SelfTest", "Crypto.SelfTest.Cipher", "Crypto.SelfTest.Hash", "Crypto.SelfTest.Protocol", "Crypto.SelfTest.PublicKey", "Crypto.SelfTest.Random", "Crypto.SelfTest.Random.Fortuna", "Crypto.SelfTest.Random.OSRNG", "Crypto.SelfTest.Util", "Crypto.SelfTest.Signature", "Crypto.Protocol", "Crypto.PublicKey", "Crypto.Signature"], 'package_dir' : { "Crypto": "lib/Crypto" }, 'ext_modules': plat_ext + [ # _fastmath (uses GNU mp library) Extension("Crypto.PublicKey._fastmath", include_dirs=['src/','/usr/include/'], libraries=['gmp'], sources=["src/_fastmath.c"]), # Hash functions Extension("Crypto.Hash._MD2", include_dirs=['src/'], sources=["src/MD2.c"]), Extension("Crypto.Hash._MD4", include_dirs=['src/'], sources=["src/MD4.c"]), Extension("Crypto.Hash._SHA256", include_dirs=['src/'], sources=["src/SHA256.c"]), Extension("Crypto.Hash._SHA224", include_dirs=['src/'], sources=["src/SHA224.c"]), Extension("Crypto.Hash._SHA384", include_dirs=['src/'], sources=["src/SHA384.c"]), Extension("Crypto.Hash._SHA512", include_dirs=['src/'], sources=["src/SHA512.c"]), Extension("Crypto.Hash._RIPEMD160", include_dirs=['src/'], sources=["src/RIPEMD160.c"], define_macros=[endianness_macro()]), # Block encryption algorithms Extension("Crypto.Cipher._AES", include_dirs=['src/'], sources=["src/AES.c"]), Extension("Crypto.Cipher._ARC2", include_dirs=['src/'], sources=["src/ARC2.c"]), Extension("Crypto.Cipher._Blowfish", include_dirs=['src/'], sources=["src/Blowfish.c"]), Extension("Crypto.Cipher._CAST", include_dirs=['src/'], sources=["src/CAST.c"]), Extension("Crypto.Cipher._DES", include_dirs=['src/', 'src/libtom/'], sources=["src/DES.c"]), Extension("Crypto.Cipher._DES3", include_dirs=['src/', 'src/libtom/'], sources=["src/DES3.c"]), # Stream ciphers Extension("Crypto.Cipher._ARC4", include_dirs=['src/'], sources=["src/ARC4.c"]), Extension("Crypto.Cipher._XOR", include_dirs=['src/'], sources=["src/XOR.c"]), # Utility modules Extension("Crypto.Util.strxor", include_dirs=['src/'], sources=['src/strxor.c']), # Counter modules Extension("Crypto.Util._counter", include_dirs=['src/'], sources=['src/_counter.c']), ] } # If we're running Python 2.3, add extra information if hasattr(core, 'setup_keywords'): if 'classifiers' in core.setup_keywords: kw['classifiers'] = [ 'Development Status :: 5 - Production/Stable', 'License :: Public Domain', 'Intended Audience :: Developers', 'Operating System :: Unix', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Security :: Cryptography', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] core.setup(**kw) def touch(path): import os, time now = time.time() try: # assume it's there os.utime(path, (now, now)) except os.error: PrintErr("Failed to update timestamp of "+path) # PY3K: Workaround for winrandom.pyd not existing during the first pass. # It needs to be there for 2to3 to fix the import in nt.py if (sys.platform == 'win32' and sys.version_info[0] == 3 and 'build' in sys.argv[1:]): PrintErr("\nSecond pass to allow 2to3 to fix nt.py. No cause for alarm.\n") touch("./lib/Crypto/Random/OSRNG/nt.py") core.setup(**kw)
mohamedhagag/community-addons
refs/heads/8.0
change_management_own_project/models/__init__.py
1
# -*- coding: utf-8 -*- # © 2015 Eficent Business and IT Consulting Services S.L. <contact@eficent.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from . import change_management
dare0021/KerasBasedSpeechClassifier
refs/heads/master
fuzzyHelper.py
1
# works with nb_classes <= 10 because lazy # TODO: resolve pathological indecision nb_classes = 0 ignoreThresh = 3 currentState = None; lastSolidState = None; solidSuffix = "solid" fluidSuffix = "fluid" timeSameInputs = 0 # kept just in case I figure out what to do with pathological indecision timeSinceSolidPush = 0 # class will change if there were ignoreThreshold attempts to change to the class already def init(num_classes, ignoreThreshold): global nb_classes, ignoreThresh nb_classes = num_classes ignoreThresh = ignoreThreshold def push(state): global nb_classes, currentState, ignoreThresh, timeSinceSolidPush, timeSameInputs, lastSolidState assert nb_classes > 0 assert state < nb_classes if currentState == None: setSolidState(state) return state if currentState.endswith(solidSuffix): if getCurrentState() == state: timeSameInputs += 1 timeSinceSolidPush = 0 return state else: timeSameInputs = 1 if ignoreThresh < 1: setSolidState(state) return state else: currentState = str(state) + fluidSuffix timeSinceSolidPush += 1 return lastSolidState elif currentState.endswith(fluidSuffix): if getCurrentState() == state: timeSameInputs += 1 if timeSameInputs > ignoreThresh: setSolidState(state) return state else: timeSinceSolidPush += 1 return lastSolidState else: timeSameInputs = 1 currentState = str(state) + fluidSuffix timeSinceSolidPush += 1 return lastSolidState else: assert "Invalid currentState" == "" def setSolidState(state): global nb_classes, currentState, lastSolidState assert nb_classes > 0 assert state < nb_classes currentState = str(state) + solidSuffix lastSolidState = getCurrentState() timeSinceSolidPush = 0 def getCurrentState(): return int(currentState[0]) # init(3, 2) # print push(1) # print push(2) # print push(2) # print push(0) # print push(0) # print push(0) # print push(1) # print push(0)
dronefly/dronefly.github.io
refs/heads/master
flask/lib/python2.7/site-packages/jinja2/environment.py
332
# -*- coding: utf-8 -*- """ jinja2.environment ~~~~~~~~~~~~~~~~~~ Provides a class that holds runtime and parsing time options. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import os import sys from jinja2 import nodes from jinja2.defaults import BLOCK_START_STRING, \ BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \ COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \ LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \ DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \ KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS from jinja2.lexer import get_lexer, TokenStream from jinja2.parser import Parser from jinja2.nodes import EvalContext from jinja2.optimizer import optimize from jinja2.compiler import generate, CodeGenerator from jinja2.runtime import Undefined, new_context, Context from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \ TemplatesNotFound, TemplateRuntimeError from jinja2.utils import import_string, LRUCache, Markup, missing, \ concat, consume, internalcode from jinja2._compat import imap, ifilter, string_types, iteritems, \ text_type, reraise, implements_iterator, implements_to_string, \ get_next, encode_filename, PY2, PYPY from functools import reduce # for direct template usage we have up to ten living environments _spontaneous_environments = LRUCache(10) # the function to create jinja traceback objects. This is dynamically # imported on the first exception in the exception handler. _make_traceback = None def get_spontaneous_environment(*args): """Return a new spontaneous environment. A spontaneous environment is an unnamed and unaccessible (in theory) environment that is used for templates generated from a string and not from the file system. """ try: env = _spontaneous_environments.get(args) except TypeError: return Environment(*args) if env is not None: return env _spontaneous_environments[args] = env = Environment(*args) env.shared = True return env def create_cache(size): """Return the cache class for the given size.""" if size == 0: return None if size < 0: return {} return LRUCache(size) def copy_cache(cache): """Create an empty copy of the given cache.""" if cache is None: return None elif type(cache) is dict: return {} return LRUCache(cache.capacity) def load_extensions(environment, extensions): """Load the extensions from the list and bind it to the environment. Returns a dict of instantiated environments. """ result = {} for extension in extensions: if isinstance(extension, string_types): extension = import_string(extension) result[extension.identifier] = extension(environment) return result def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_string != \ environment.comment_start_string, 'block, variable and comment ' \ 'start strings must be different' assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ 'newline_sequence set to unknown line ending string.' return environment class Environment(object): r"""The core component of Jinja is the `Environment`. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior. Here are the possible initialization parameters: `block_start_string` The string marking the beginning of a block. Defaults to ``'{%'``. `block_end_string` The string marking the end of a block. Defaults to ``'%}'``. `variable_start_string` The string marking the beginning of a print statement. Defaults to ``'{{'``. `variable_end_string` The string marking the end of a print statement. Defaults to ``'}}'``. `comment_start_string` The string marking the beginning of a comment. Defaults to ``'{#'``. `comment_end_string` The string marking the end of a comment. Defaults to ``'#}'``. `line_statement_prefix` If given and a string, this will be used as prefix for line based statements. See also :ref:`line-statements`. `line_comment_prefix` If given and a string, this will be used as prefix for line based comments. See also :ref:`line-statements`. .. versionadded:: 2.2 `trim_blocks` If this is set to ``True`` the first newline after a block is removed (block, not variable tag!). Defaults to `False`. `lstrip_blocks` If this is set to ``True`` leading spaces and tabs are stripped from the start of a line to a block. Defaults to `False`. `newline_sequence` The sequence that starts a newline. Must be one of ``'\r'``, ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a useful default for Linux and OS X systems as well as web applications. `keep_trailing_newline` Preserve the trailing newline when rendering templates. The default is ``False``, which causes a single newline, if present, to be stripped from the end of the template. .. versionadded:: 2.7 `extensions` List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at :ref:`the extensions documentation <jinja-extensions>`. `optimized` should the optimizer be enabled? Default is `True`. `undefined` :class:`Undefined` or a subclass of it that is used to represent undefined values in the template. `finalize` A callable that can be used to process the result of a variable expression before it is output. For example one can convert `None` implicitly into an empty string here. `autoescape` If set to true the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping see :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return `True` or `False` depending on autoescape should be enabled by default. .. versionchanged:: 2.4 `autoescape` can now be a function `loader` The template loader for this environment. `cache_size` The size of the cache. Per default this is ``400`` which means that if more than 400 templates are loaded the loader will clean out the least recently used template. If the cache size is set to ``0`` templates are recompiled all the time, if the cache size is ``-1`` the cache will not be cleaned. .. versionchanged:: 2.8 The cache size was increased to 400 from a low 50. `auto_reload` Some loaders load templates from locations where the template sources may change (ie: file system or database). If `auto_reload` is set to `True` (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it's possible to disable that. `bytecode_cache` If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don't have to be parsed if they were not changed. See :ref:`bytecode-cache` for more information. """ #: if this environment is sandboxed. Modifying this variable won't make #: the environment sandboxed though. For a real sandboxed environment #: have a look at jinja2.sandbox. This flag alone controls the code #: generation by the compiler. sandboxed = False #: True if the environment is just an overlay overlayed = False #: the environment this environment is linked to if it is an overlay linked_to = None #: shared environments have this set to `True`. A shared environment #: must not be modified shared = False #: these are currently EXPERIMENTAL undocumented features. exception_handler = None exception_formatter = None #: the class that is used for code generation. See #: :class:`~jinja2.compiler.CodeGenerator` for more information. code_generator_class = CodeGenerator #: the context class thatis used for templates. See #: :class:`~jinja2.runtime.Context` for more information. context_class = Context def __init__(self, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, lstrip_blocks=LSTRIP_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, keep_trailing_newline=KEEP_TRAILING_NEWLINE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False, loader=None, cache_size=400, auto_reload=True, bytecode_cache=None): # !!Important notice!! # The constructor accepts quite a few arguments that should be # passed by keyword rather than position. However it's important to # not change the order of arguments because it's used at least # internally in those cases: # - spontaneous environments (i18n extension and Template) # - unittests # If parameter changes are required only add parameters at the end # and don't change the arguments (or the defaults!) of the arguments # existing already. # lexer / parser information self.block_start_string = block_start_string self.block_end_string = block_end_string self.variable_start_string = variable_start_string self.variable_end_string = variable_end_string self.comment_start_string = comment_start_string self.comment_end_string = comment_end_string self.line_statement_prefix = line_statement_prefix self.line_comment_prefix = line_comment_prefix self.trim_blocks = trim_blocks self.lstrip_blocks = lstrip_blocks self.newline_sequence = newline_sequence self.keep_trailing_newline = keep_trailing_newline # runtime information self.undefined = undefined self.optimized = optimized self.finalize = finalize self.autoescape = autoescape # defaults self.filters = DEFAULT_FILTERS.copy() self.tests = DEFAULT_TESTS.copy() self.globals = DEFAULT_NAMESPACE.copy() # set the loader provided self.loader = loader self.cache = create_cache(cache_size) self.bytecode_cache = bytecode_cache self.auto_reload = auto_reload # load extensions self.extensions = load_extensions(self, extensions) _environment_sanity_check(self) def add_extension(self, extension): """Adds an extension after the environment was created. .. versionadded:: 2.5 """ self.extensions.update(load_extensions(self, [extension])) def extend(self, **attributes): """Add the items to the instance of the environment if they do not exist yet. This is used by :ref:`extensions <writing-extensions>` to register callbacks and configuration values without breaking inheritance. """ for key, value in iteritems(attributes): if not hasattr(self, key): setattr(self, key, value) def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_blocks=missing, lstrip_blocks=missing, extensions=missing, optimized=missing, undefined=missing, finalize=missing, autoescape=missing, loader=missing, cache_size=missing, auto_reload=missing, bytecode_cache=missing): """Create a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions. Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through. """ args = dict(locals()) del args['self'], args['cache_size'], args['extensions'] rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.overlayed = True rv.linked_to = self for key, value in iteritems(args): if value is not missing: setattr(rv, key, value) if cache_size is not missing: rv.cache = create_cache(cache_size) else: rv.cache = copy_cache(self.cache) rv.extensions = {} for key, value in iteritems(self.extensions): rv.extensions[key] = value.bind(rv) if extensions is not missing: rv.extensions.update(load_extensions(rv, extensions)) return _environment_sanity_check(rv) lexer = property(get_lexer, doc="The lexer for this environment.") def iter_extensions(self): """Iterates over the extensions by priority.""" return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) def getitem(self, obj, argument): """Get an item or attribute of an object but prefer the item.""" try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, string_types): try: attr = str(argument) except Exception: pass else: try: return getattr(obj, attr) except AttributeError: pass return self.undefined(obj=obj, name=argument) def getattr(self, obj, attribute): """Get an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a bytestring. """ try: return getattr(obj, attribute) except AttributeError: pass try: return obj[attribute] except (TypeError, LookupError, AttributeError): return self.undefined(obj=obj, name=attribute) def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None): """Invokes a filter on a value the same way the compiler does it. .. versionadded:: 2.7 """ func = self.filters.get(name) if func is None: raise TemplateRuntimeError('no filter named %r' % name) args = [value] + list(args or ()) if getattr(func, 'contextfilter', False): if context is None: raise TemplateRuntimeError('Attempted to invoke context ' 'filter without context') args.insert(0, context) elif getattr(func, 'evalcontextfilter', False): if eval_ctx is None: if context is not None: eval_ctx = context.eval_ctx else: eval_ctx = EvalContext(self) args.insert(0, eval_ctx) elif getattr(func, 'environmentfilter', False): args.insert(0, self) return func(*args, **(kwargs or {})) def call_test(self, name, value, args=None, kwargs=None): """Invokes a test on a value the same way the compiler does it. .. versionadded:: 2.7 """ func = self.tests.get(name) if func is None: raise TemplateRuntimeError('no test named %r' % name) return func(value, *(args or ()), **(kwargs or {})) @internalcode def parse(self, source, name=None, filename=None): """Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates. If you are :ref:`developing Jinja2 extensions <writing-extensions>` this gives you a good overview of the node tree generated. """ try: return self._parse(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source) def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, encode_filename(filename)).parse() def lex(self, source, name=None, filename=None): """Lex the given sourcecode and return a generator that yields tokens as tuples in the form ``(lineno, token_type, value)``. This can be useful for :ref:`extension development <writing-extensions>` and debugging templates. This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the :meth:`preprocess` method. """ source = text_type(source) try: return self.lexer.tokeniter(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source) def preprocess(self, source, name=None, filename=None): """Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but *not* for :meth:`lex` because there you usually only want the actual source tokenized. """ return reduce(lambda s, e: e.preprocess(s, name, filename), self.iter_extensions(), text_type(source)) def _tokenize(self, source, name, filename=None, state=None): """Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. """ source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(source, name, filename, state) for ext in self.iter_extensions(): stream = ext.filter_stream(stream) if not isinstance(stream, TokenStream): stream = TokenStream(stream, name, filename) return stream def _generate(self, source, name, filename, defer_init=False): """Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5 """ return generate(source, self, name, filename, defer_init=defer_init) def _compile(self, source, filename): """Internal hook that can be overridden to hook a different compile method in. .. versionadded:: 2.5 """ return compile(source, filename, 'exec') @internalcode def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted. The return value of this method is a python code object. If the `raw` parameter is `True` the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally. `defer_init` is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set. .. versionadded:: 2.4 `defer_init` parameter added. """ source_hint = None try: if isinstance(source, string_types): source_hint = source source = self._parse(source, name, filename) if self.optimized: source = optimize(source, self) source = self._generate(source, name, filename, defer_init=defer_init) if raw: return source if filename is None: filename = '<template>' else: filename = encode_filename(filename) return self._compile(source, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source_hint) def compile_expression(self, source, undefined_to_none=True): """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1 """ parser = Parser(self, source, state='variable') exc_info = None try: expr = parser.parse_expression() if not parser.stream.eos: raise TemplateSyntaxError('chunk after expression', parser.stream.current.lineno, None, None) expr.set_environment(self) except TemplateSyntaxError: exc_info = sys.exc_info() if exc_info is not None: self.handle_exception(exc_info, source_hint=source) body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] template = self.from_string(nodes.Template(body, lineno=1)) return TemplateExpression(template, undefined_to_none) def compile_templates(self, target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False): """Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, `zip` can be set to ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. If `py_compile` is set to `True` .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don't give much benefit. .. versionadded:: 2.4 """ from jinja2.loaders import ModuleLoader if log_function is None: log_function = lambda x: None if py_compile: if not PY2 or PYPY: from warnings import warn warn(Warning('py_compile has no effect on pypy or Python 3')) py_compile = False else: import imp import marshal py_header = imp.get_magic() + \ u'\xff\xff\xff\xff'.encode('iso-8859-15') # Python 3.3 added a source filesize to the header if sys.version_info >= (3, 3): py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15') def write_file(filename, data, mode): if zip: info = ZipInfo(filename) info.external_attr = 0o755 << 16 zip_file.writestr(info, data) else: f = open(os.path.join(target, filename), mode) try: f.write(data) finally: f.close() if zip is not None: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]) log_function('Compiling into Zip archive "%s"' % target) else: if not os.path.isdir(target): os.makedirs(target) log_function('Compiling into folder "%s"' % target) try: for name in self.list_templates(extensions, filter_func): source, filename, _ = self.loader.get_source(self, name) try: code = self.compile(source, name, filename, True, True) except TemplateSyntaxError as e: if not ignore_errors: raise log_function('Could not compile "%s": %s' % (name, e)) continue filename = ModuleLoader.get_module_filename(name) if py_compile: c = self._compile(code, encode_filename(filename)) write_file(filename + 'c', py_header + marshal.dumps(c), 'wb') log_function('Byte-compiled "%s" as %s' % (name, filename + 'c')) else: write_file(filename, code, 'w') log_function('Compiled "%s" as %s' % (name, filename)) finally: if zip: zip_file.close() log_function('Finished compiling templates') def list_templates(self, extensions=None, filter_func=None): """Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either `extensions` is set to a list of file extensions for templates, or a `filter_func` can be provided which is a callable that is passed a template name and should return `True` if it should end up in the result list. If the loader does not support that, a :exc:`TypeError` is raised. .. versionadded:: 2.4 """ x = self.loader.list_templates() if extensions is not None: if filter_func is not None: raise TypeError('either extensions or filter_func ' 'can be passed, but not both') filter_func = lambda x: '.' in x and \ x.rsplit('.', 1)[1] in extensions if filter_func is not None: x = list(ifilter(filter_func, x)) return x def handle_exception(self, exc_info=None, rendered=False, source_hint=None): """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ global _make_traceback if exc_info is None: exc_info = sys.exc_info() # the debugging module is imported when it's used for the first time. # we're doing a lot of stuff there and for applications that do not # get any exceptions in template rendering there is no need to load # all of that. if _make_traceback is None: from jinja2.debug import make_traceback as _make_traceback traceback = _make_traceback(exc_info, source_hint) if rendered and self.exception_formatter is not None: return self.exception_formatter(traceback) if self.exception_handler is not None: self.exception_handler(traceback) exc_type, exc_value, tb = traceback.standard_exc_info reraise(exc_type, exc_value, tb) def join_path(self, template, parent): """Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here. """ return template @internalcode def _load_template(self, name, globals): if self.loader is None: raise TypeError('no loader for this environment specified') try: # use abs path for cache key cache_key = self.loader.get_source(self, name)[1] except RuntimeError: # if loader does not implement get_source() cache_key = None # if template is not file, use name for cache key if cache_key is None: cache_key = name if self.cache is not None: template = self.cache.get(cache_key) if template is not None and (not self.auto_reload or template.is_up_to_date): return template template = self.loader.load(self, name, globals) if self.cache is not None: self.cache[cache_key] = template return template @internalcode def get_template(self, name, parent=None, globals=None): """Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a :class:`Template`. If the `parent` parameter is not `None`, :meth:`join_path` is called to get the real template name before loading. The `globals` parameter can be used to provide template wide globals. These variables are available in the context at render time. If the template does not exist a :exc:`TemplateNotFound` exception is raised. .. versionchanged:: 2.4 If `name` is a :class:`Template` object it is returned from the function unchanged. """ if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) return self._load_template(name, self.make_globals(globals)) @internalcode def select_template(self, names, parent=None, globals=None): """Works like :meth:`get_template` but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a :exc:`TemplatesNotFound` exception. .. versionadded:: 2.3 .. versionchanged:: 2.4 If `names` contains a :class:`Template` object it is returned from the function unchanged. """ if not names: raise TemplatesNotFound(message=u'Tried to select from an empty list ' u'of templates.') globals = self.make_globals(globals) for name in names: if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) try: return self._load_template(name, globals) except TemplateNotFound: pass raise TemplatesNotFound(names) @internalcode def get_or_select_template(self, template_name_or_list, parent=None, globals=None): """Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3 """ if isinstance(template_name_or_list, string_types): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals) def from_string(self, source, globals=None, template_class=None): """Load a template from a string. This parses the source given and returns a :class:`Template` object. """ globals = self.make_globals(globals) cls = template_class or self.template_class return cls.from_code(self, self.compile(source), globals, None) def make_globals(self, d): """Return a dict for the globals.""" if not d: return self.globals return dict(self.globals, **d) class Template(object): """The central template object. This class represents a compiled template and is used to evaluate it. Normally the template object is generated from an :class:`Environment` but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it's not possible to specify a loader. Every template object has a few methods and members that are guaranteed to exist. However it's important that a template object should be considered immutable. Modifications on the object are not supported. Template objects created from the constructor rather than an environment do have an `environment` attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings. >>> template = Template('Hello {{ name }}!') >>> template.render(name='John Doe') == u'Hello John Doe!' True >>> stream = template.stream(name='John Doe') >>> next(stream) == u'Hello John Doe!' True >>> next(stream) Traceback (most recent call last): ... StopIteration """ def __new__(cls, source, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, lstrip_blocks=LSTRIP_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, keep_trailing_newline=KEEP_TRAILING_NEWLINE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False): env = get_spontaneous_environment( block_start_string, block_end_string, variable_start_string, variable_end_string, comment_start_string, comment_end_string, line_statement_prefix, line_comment_prefix, trim_blocks, lstrip_blocks, newline_sequence, keep_trailing_newline, frozenset(extensions), optimized, undefined, finalize, autoescape, None, 0, False, None) return env.from_string(source, template_class=cls) @classmethod def from_code(cls, environment, code, globals, uptodate=None): """Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object. """ namespace = { 'environment': environment, '__file__': code.co_filename } exec(code, namespace) rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv @classmethod def from_module_dict(cls, environment, module_dict, globals): """Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4 """ return cls._from_namespace(environment, module_dict, globals) @classmethod def _from_namespace(cls, environment, namespace, globals): t = object.__new__(cls) t.environment = environment t.globals = globals t.name = namespace['name'] t.filename = namespace['__file__'] t.blocks = namespace['blocks'] # render function and module t.root_render_func = namespace['root'] t._module = None # debug and loader helpers t._debug_info = namespace['debug_info'] t._uptodate = None # store the reference namespace['environment'] = environment namespace['__jinja_template__'] = t return t def render(self, *args, **kwargs): """This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights='that say nih') template.render({'knights': 'that say nih'}) This will return the rendered template as unicode string. """ vars = dict(*args, **kwargs) try: return concat(self.root_render_func(self.new_context(vars))) except Exception: exc_info = sys.exc_info() return self.environment.handle_exception(exc_info, True) def stream(self, *args, **kwargs): """Works exactly like :meth:`generate` but returns a :class:`TemplateStream`. """ return TemplateStream(self.generate(*args, **kwargs)) def generate(self, *args, **kwargs): """For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings. It accepts the same arguments as :meth:`render`. """ vars = dict(*args, **kwargs) try: for event in self.root_render_func(self.new_context(vars)): yield event except Exception: exc_info = sys.exc_info() else: return yield self.environment.handle_exception(exc_info, True) def new_context(self, vars=None, shared=False, locals=None): """Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as it to the context without adding the globals. `locals` can be a dict of local variables for internal usage. """ return new_context(self.environment, self.name, self.blocks, vars, shared, self.globals, locals) def make_module(self, vars=None, shared=False, locals=None): """This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method. """ return TemplateModule(self, self.new_context(vars, shared, locals)) @property def module(self): """The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> str(t.module) '23' >>> t.module.foo() == u'42' True """ if self._module is not None: return self._module self._module = rv = self.make_module() return rv def get_corresponding_lineno(self, lineno): """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1 @property def is_up_to_date(self): """If this variable is `False` there is a newer version available.""" if self._uptodate is None: return True return self._uptodate() @property def debug_info(self): """The debug info mapping.""" return [tuple(imap(int, x.split('='))) for x in self._debug_info.split('&')] def __repr__(self): if self.name is None: name = 'memory:%x' % id(self) else: name = repr(self.name) return '<%s %s>' % (self.__class__.__name__, name) @implements_to_string class TemplateModule(object): """Represents an imported template. All the exported names of the template are available as attributes on this object. Additionally converting it into an unicode- or bytestrings renders the contents. """ def __init__(self, template, context): self._body_stream = list(template.root_render_func(context)) self.__dict__.update(context.get_exported()) self.__name__ = template.name def __html__(self): return Markup(concat(self._body_stream)) def __str__(self): return concat(self._body_stream) def __repr__(self): if self.__name__ is None: name = 'memory:%x' % id(self) else: name = repr(self.__name__) return '<%s %s>' % (self.__class__.__name__, name) class TemplateExpression(object): """The :meth:`jinja2.Environment.compile_expression` method returns an instance of this object. It encapsulates the expression-like access to the template with an expression it wraps. """ def __init__(self, template, undefined_to_none): self._template = template self._undefined_to_none = undefined_to_none def __call__(self, *args, **kwargs): context = self._template.new_context(dict(*args, **kwargs)) consume(self._template.root_render_func(context)) rv = context.vars['result'] if self._undefined_to_none and isinstance(rv, Undefined): rv = None return rv @implements_iterator class TemplateStream(object): """A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one unicode string is yielded. If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration. """ def __init__(self, gen): self._gen = gen self.disable_buffering() def dump(self, fp, encoding=None, errors='strict'): """Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specify an `encoding`. Example usage:: Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') """ close = False if isinstance(fp, string_types): if encoding is None: encoding = 'utf-8' fp = open(fp, 'wb') close = True try: if encoding is not None: iterable = (x.encode(encoding, errors) for x in self) else: iterable = self if hasattr(fp, 'writelines'): fp.writelines(iterable) else: for item in iterable: fp.write(item) finally: if close: fp.close() def disable_buffering(self): """Disable the output buffering.""" self._next = get_next(self._gen) self.buffered = False def enable_buffering(self, size=5): """Enable buffering. Buffer `size` items before yielding them.""" if size <= 1: raise ValueError('buffer size too small') def generator(next): buf = [] c_size = 0 push = buf.append while 1: try: while c_size < size: c = next() push(c) if c: c_size += 1 except StopIteration: if not c_size: return yield concat(buf) del buf[:] c_size = 0 self.buffered = True self._next = get_next(generator(get_next(self._gen))) def __iter__(self): return self def __next__(self): return self._next() # hook in default template class. if anyone reads this comment: ignore that # it's possible to use custom templates ;-) Environment.template_class = Template
masterdon/Veil-Evasion
refs/heads/master
tools/pyherion.py
12
#!/usr/bin/python """ PyHerion 1.0 By: @harmj0y Python 'crypter' that builds an dynamic AES/base64 encoded launcher (with a random key) that's decoded/decrypted in memory and then executed. Standalone version of the same functionality integrated into Veil, in ./modules/common/encryption.py """ from Crypto.Cipher import AES import base64, random, string, sys # crypto config stuff BLOCK_SIZE = 32 PADDING = '{' # used for separting out the import lines imports = list() output = list() # check to make sure it's being called properly if len(sys.argv) < 2 or len(sys.argv) > 3: print "\nPyherion 1.0\n\n\tusage:\t./pyherion.py intputfile [outputfile]\n" sys.exit() # returns a random string/key of "bytes" length def randKey(bytes): return ''.join(random.choice(string.ascii_letters + string.digits + "{}!@#$^&()*&[]|,./?") for x in range(bytes)) # random 3 letter variable generator def randVar(): return ''.join(random.choice(string.ascii_letters) for x in range(3)) + "_" + ''.join(random.choice("0123456789") for x in range(3)) # one-liner to sufficiently pad the text to be encrypted pad = lambda s: str(s) + (BLOCK_SIZE - len(str(s)) % BLOCK_SIZE) * PADDING # one-liner to encrypt a code block then base64 it EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) # generate our key and initialization vector key = randKey(32) iv = randKey(16) input = open(sys.argv[1]).readlines() pieces = sys.argv[1].split(".") # build our new filename, "payload.py" -> "payload_crypted.py" outputName = ".".join(pieces[:-2]) + pieces[-2] + "_crypted." + pieces[-1] # check if the output name was specified, otherwise use the one built above if len(sys.argv) == 3: outputName = sys.argv[2] f = open(outputName, 'w') # Detect if the passed argument is a python file if pieces[-1] == "py": # separate imports from code- this is because pyinstaller needs to # know what imports to package with the .exe at compile time. # Otherwise the imports in the exec() string won't work for line in input: if not line.startswith("#"): # ignore commented imports... if "import" in line: imports.append(line.strip()) else: output.append(line) # build our AES cipher cipherEnc = AES.new(key) # encrypt the input file (less the imports) encrypted = EncodeAES(cipherEnc, "".join(output)) b64var = randVar() aesvar = randVar() # randomize our base64 and AES importing variable imports.append("from base64 import b64decode as %s" %(b64var)) imports.append("from Crypto.Cipher import AES as %s" %(aesvar)) # shuffle up our imports random.shuffle(imports) f.write(";".join(imports) + "\n") # build the exec() launcher f.write("exec(%s(\"%s\"))" % (b64var,base64.b64encode("exec(%s.new(\"%s\").decrypt(%s(\"%s\")).rstrip('{'))\n" %(aesvar,key,b64var,encrypted)))) f.close() else: print "\nonly python files can be used as input files" sys.exit() print "\n\tCrypted output written to %s\n" % (outputName)
evildmp/django-cms
refs/heads/master
cms/test_utils/project/extensionapp/cms_toolbars.py
5
# -*- coding: utf-8 -*- from cms.api import get_page_draft from cms.test_utils.project.extensionapp.models import MyTitleExtension, MyPageExtension from cms.utils.page_permissions import user_can_change_page from cms.utils.urlutils import admin_reverse from django.core.urlresolvers import NoReverseMatch from django.utils.translation import ugettext_lazy as _ from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar @toolbar_pool.register class MyTitleExtensionToolbar(CMSToolbar): def populate(self): # always use draft if we have a page self.page = get_page_draft(self.request.current_page) if not self.page: # Nothing to do return if user_can_change_page(self.request.user, page=self.page): try: mytitleextension = MyTitleExtension.objects.get(extended_object_id=self.page.id) except MyTitleExtension.DoesNotExist: mytitleextension = None try: if mytitleextension: url = admin_reverse('extensionapp_mytitleextension_change', args=(mytitleextension.pk,)) else: url = admin_reverse('extensionapp_mytitleextension_add') + '?extended_object=%s' % self.page.pk except NoReverseMatch: # not in urls pass else: not_edit_mode = not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page') current_page_menu.add_modal_item(_('Title Extension'), url=url, disabled=not_edit_mode) @toolbar_pool.register class MyPageExtensionToolbar(CMSToolbar): supported_apps = ('cms.test_utils.project.extensionapp.cms_toolbar', 'cms.test_utils.project.placeholderapp') def populate(self): # always use draft if we have a page self.page = get_page_draft(self.request.current_page) if not self.page: # Nothing to do return if user_can_change_page(self.request.user, page=self.page): try: mypageextension = MyPageExtension.objects.get(extended_object_id=self.page.id) except MyPageExtension.DoesNotExist: mypageextension = None try: if mypageextension: url = admin_reverse('extensionapp_mypageextension_change', args=(mypageextension.pk,)) else: url = admin_reverse('extensionapp_mypageextension_add') + '?extended_object=%s' % self.page.pk except NoReverseMatch: # not in urls pass else: not_edit_mode = not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page') current_page_menu.add_modal_item(_('Page Extension'), url=url, disabled=not_edit_mode)
molebot/brython
refs/heads/master
www/src/Lib/unittest/test/test_break.py
785
import gc import io import os import sys import signal import weakref import unittest @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreak(unittest.TestCase): def setUp(self): self._default_handler = signal.getsignal(signal.SIGINT) def tearDown(self): signal.signal(signal.SIGINT, self._default_handler) unittest.signals._results = weakref.WeakKeyDictionary() unittest.signals._interrupt_handler = None def testInstallHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(unittest.signals._interrupt_handler.called) def testRegisterResult(self): result = unittest.TestResult() unittest.registerResult(result) for ref in unittest.signals._results: if ref is result: break elif ref is not result: self.fail("odd object in result set") else: self.fail("result not found") def testInterruptCaught(self): default_handler = signal.getsignal(signal.SIGINT) result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.breakCaught) def testSecondInterrupt(self): result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught) def testTwoResults(self): unittest.installHandler() result = unittest.TestResult() unittest.registerResult(result) new_handler = signal.getsignal(signal.SIGINT) result2 = unittest.TestResult() unittest.registerResult(result2) self.assertEqual(signal.getsignal(signal.SIGINT), new_handler) result3 = unittest.TestResult() def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.shouldStop) self.assertTrue(result2.shouldStop) self.assertFalse(result3.shouldStop) def testHandlerReplacedButCalled(self): # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt") def testRunner(self): # Creating a TextTestRunner with the appropriate argument should # register the TextTestResult it creates runner = unittest.TextTestRunner(stream=io.StringIO()) result = runner.run(unittest.TestSuite()) self.assertIn(result, unittest.signals._results) def testWeakReferences(self): # Calling registerResult on a result should not keep it alive result = unittest.TestResult() unittest.registerResult(result) ref = weakref.ref(result) del result # For non-reference counting implementations gc.collect();gc.collect() self.assertIsNone(ref()) def testRemoveResult(self): result = unittest.TestResult() unittest.registerResult(result) unittest.installHandler() self.assertTrue(unittest.removeResult(result)) # Should this raise an error instead? self.assertFalse(unittest.removeResult(unittest.TestResult())) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass self.assertFalse(result.shouldStop) def testMainInstallsHandler(self): failfast = object() test = object() verbosity = object() result = object() default_handler = signal.getsignal(signal.SIGINT) class FakeRunner(object): initArgs = [] runArgs = [] def __init__(self, *args, **kwargs): self.initArgs.append((args, kwargs)) def run(self, test): self.runArgs.append(test) return result class Program(unittest.TestProgram): def __init__(self, catchbreak): self.exit = False self.verbosity = verbosity self.failfast = failfast self.catchbreak = catchbreak self.testRunner = FakeRunner self.test = test self.result = None p = Program(False) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast, 'warnings': None})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) FakeRunner.initArgs = [] FakeRunner.runArgs = [] p = Program(True) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast, 'warnings': None})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) # check that calling removeHandler multiple times has no ill-effect unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandlerAsDecorator(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() @unittest.removeHandler def test(): self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) test() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)
niphlod/w2p_tvseries
refs/heads/master
modules/requests/packages/chardet/cp949prober.py
2800
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library 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 2.1 of the License, or (at your option) any later version. # # This library 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 this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCKRDistributionAnalysis from .mbcssm import CP949SMModel class CP949Prober(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(CP949SMModel) # NOTE: CP949 is a superset of EUC-KR, so the distribution should be # not different. self._mDistributionAnalyzer = EUCKRDistributionAnalysis() self.reset() def get_charset_name(self): return "CP949"
google/contentbox
refs/heads/master
third_party/requests/packages/chardet/cp949prober.py
2800
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library 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 2.1 of the License, or (at your option) any later version. # # This library 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 this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCKRDistributionAnalysis from .mbcssm import CP949SMModel class CP949Prober(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(CP949SMModel) # NOTE: CP949 is a superset of EUC-KR, so the distribution should be # not different. self._mDistributionAnalyzer = EUCKRDistributionAnalysis() self.reset() def get_charset_name(self): return "CP949"
Karl-Marka/data-mining
refs/heads/master
scleroderma-prediction/Predict_PAH.py
1
from pandas import DataFrame, read_csv from sklearn.cross_validation import train_test_split from sklearn.feature_selection import f_classif import matplotlib.pyplot as plt from numpy import mean, array from sklearn import linear_model from pylab import figure, xlim, ylim, ylabel, xlabel, title, tick_params, axvspan, gca, plot, figtext, subplot, legend from matplotlib.ticker import MultipleLocator, FormatStrFormatter data = read_csv('x.txt', header = 0, index_col = 0, sep = '\t') data = data.T #print(X.head(2)) labels = read_csv('y.txt', header = None, sep = '\t') labels = labels.unstack().tolist() #print(Y) result = f_classif(data, labels) Fval = result[0] Fval = list(Fval) data.ix['F'] = Fval data = data.T data = data.sort_values('F', axis = 0, ascending=False) data = data.T data = data.drop(['F']) def closeFunc(): print('''Type 'quit' and press enter to exit program''') answer = input(': ') if answer == 'quit': quit() else: closeFunc() noOfOligos = len(data.columns) #noOfOligos = 100 clf = linear_model.LogisticRegression(random_state = 5) in_sample_errors = [] test_errors = [] def createPlot(y1, y2, limit): xFormatter = FormatStrFormatter('%d') fig = figure() xlim(1, limit) x = list(range(1,limit)) print(x) xlabel("No. of parameters") ylabel("R-squared error") title("In-sample error and testing error") tick_params( axis='x', which='both', bottom='off', top='off', labelbottom='on') gca().set_position((.1, .3, .8, .6)) #figtext(.04, .05, content) ax = subplot(111) plot(x, y1, 'orange', label = 'In-sample error') plot( x, y2, 'red', label = 'Testing error') ax.xaxis.set_major_formatter(xFormatter) legend(bbox_to_anchor=(0.85, 0.75), loc=4, borderaxespad=0.1) fig.savefig('PAH_errorgraph.png') RSE = 1 turn = 1 while turn < (noOfOligos - 1): X_train, X_test, y_train, y_test = train_test_split(data, labels, random_state=5) result = f_classif(X_train, y_train) Fval = result[0] Fval = list(Fval) X_train.ix['F'] = Fval X_test.ix['F'] = Fval X_train = X_train.T X_test = X_test.T X_train = X_train.sort_values('F', axis = 0, ascending=False) X_test = X_test.sort_values('F', axis = 0, ascending=False) X_train = X_train.T X_test = X_test.T X_train = X_train.drop(['F']) X_test = X_test.drop(['F']) X_train = X_train.iloc[:,0:turn] X_test = X_test.iloc[:,0:turn] clf.fit(X_train, y_train) train_predictions = clf.predict(X_train) test_predictions = clf.predict(X_test) in_sample_error = mean((train_predictions - y_train)**2) test_error = mean((test_predictions - y_test)**2) if test_error < RSE: RSE = test_error in_sample_errors.append(in_sample_error) test_errors.append(test_error) #print(train_predictions) #print(y_train) #print(in_sample_error) #print(test_error) print((noOfOligos-turn), 'Parameters left.', 'Current RSE:', RSE) turn += 1 #in_sample_errors = array(in_sample_errors) #test_errors = array(test_errors) #print(in_sample_errors) #print(test_errors) createPlot(in_sample_errors, test_errors, noOfOligos-1) print(RSE) closeFunc()
alebcay/namebench
refs/heads/master
libnamebench/config_test.py
173
#!/usr/bin/env python # Copyright 2009 Google Inc. All Rights Reserved. # # 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. """Tests for the config module.""" __author__ = 'tstromberg@google.com (Thomas Stromberg)' import unittest import config import sys sys.path.append('..') import third_party class ConfigTest(unittest.TestCase): def testParseFullLine(self): line = 'NTT (2) # y.ns.gin.ntt.net,39.569,-104.8582 (Englewood/CO/US)' expected = {'name': 'NTT (2)', 'service': 'NTT', 'lon': '-104.8582', 'instance': '2', 'country_code': 'US', 'lat': '39.569', 'hostname': 'y.ns.gin.ntt.net'} self.assertEquals(config._ParseServerValue(line), expected) def testOpenDNSLine(self): line = 'OpenDNS # resolver2.opendns.com' expected = {'name': 'OpenDNS', 'service': 'OpenDNS', 'ip': '208.67.220.220', 'lon': None, 'instance': None, 'country_code': None, 'lat': None, 'hostname': 'resolver2.opendns.com'} self.assertEquals(config._ParseServerValue(line), expected) def testLineWithNoRegion(self): line = 'Level/GTEI-2 (3) # vnsc-bak.sys.gtei.net,38.0,-97.0 (US) ' expected = {'name': 'Level/GTEI-2 (3)', 'service': 'Level/GTEI-2', 'lon': '-97.0', 'instance': '3', 'country_code': 'US', 'lat': '38.0', 'hostname': 'vnsc-bak.sys.gtei.net'} self.assertEquals(config._ParseServerValue(line), expected) if __name__ == '__main__': unittest.main()
oihane/odoo
refs/heads/8.0
addons/marketing_crm/models/__init__.py
378
# -*- coding: utf-8 -*- import res_config
xuru/pyvisdk
refs/heads/master
pyvisdk/do/profile_execute_result.py
1
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def ProfileExecuteResult(vim, *args, **kwargs): '''The ProfileExecuteResult data object contains the results from a HostProfile.ExecuteHostProfile operation.''' obj = vim.client.factory.create('ns0:ProfileExecuteResult') # do some validation checking... if (len(args) + len(kwargs)) < 1: raise IndexError('Expected at least 2 arguments got: %d' % len(args)) required = [ 'status' ] optional = [ 'configSpec', 'error', 'inapplicablePath', 'requireInput', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
rosmo/ansible
refs/heads/devel
test/units/modules/network/edgeos/edgeos_module.py
52
# (c) 2018 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestEdgeosModule(ModuleTestCase): def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False): self.load_fixtures(commands) if failed: result = self.failed() self.assertTrue(result['failed'], result) else: result = self.changed(changed) self.assertEqual(result['changed'], changed, result) if commands is not None: if sort: self.assertEqual(sorted(commands), sorted(result['commands']), result['commands']) else: self.assertEqual(commands, result['commands'], result['commands']) return result def failed(self): with self.assertRaises(AnsibleFailJson) as exc: self.module.main() result = exc.exception.args[0] self.assertTrue(result['failed'], result) return result def changed(self, changed=False): with self.assertRaises(AnsibleExitJson) as exc: self.module.main() result = exc.exception.args[0] self.assertEqual(result['changed'], changed, result) return result def load_fixtures(self, commands=None): pass
SmartInfrastructures/fuel-web-dev
refs/heads/master
nailgun/nailgun/test/unit/test_assignment_validator.py
6
# Copyright 2014 Mirantis, 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. from nailgun.api.v1.validators.assignment import NodeAssignmentValidator from nailgun.errors import errors from nailgun.test.base import BaseUnitTest class TestNodeAssignmentValidator(BaseUnitTest): validator = NodeAssignmentValidator def setUp(self): self.models = { 'settings': { 'parent': { 'child': { 'value': 1 } } } } def test_check_roles_requirement_equal(self): roles = ['test'] roles_metadata = { 'test': { 'depends': [ { 'condition': 'settings:parent.child.value == 1', 'warning': 'error' } ] } } self.validator.check_roles_requirement( roles, roles_metadata, self.models) def test_check_roles_requirement_not_equal(self): roles = ['test'] roles_metadata = { 'test': { 'depends': [ { 'condition': "settings:parent.child.value != 'x'", 'warning': 'error' } ] } } self.validator.check_roles_requirement( roles, roles_metadata, self.models) def test_check_roles_requirement_failed(self): roles = ['test'] # wrong child value with self.assertRaises(errors.InvalidData): roles_metadata = { 'test': { 'depends': [ { 'condition': 'settings:parent.child.value == 0', 'warning': 'error' } ] } } self.validator.check_roles_requirement( roles, roles_metadata, self.models) def test_validate_collection_update_schema_requirements(self): self.assertRaises( errors.InvalidData, self.validator.validate_collection_update, '[{}]') self.assertRaises( errors.InvalidData, self.validator.validate_collection_update, '[{"id": 1}]') self.assertRaises( errors.InvalidData, self.validator.validate_collection_update, '[{"roles": []}]')
caiomartini/SonarCommitAnalyzer
refs/heads/master
utils.py
1
import sys import http.client import os import shutil import subprocess import json def print_(text): """ Function to print and flush console. """ print(text) sys.stdout.flush() def verify_sonar_response(url): """ Function to verify SonarQube is running on server. """ print_(">> Verificando se SonarQube esta em execucao no servidor ...") try: http_url = url.replace("http://", "") sonarhttp = http.client.HTTPConnection(http_url, timeout=10) sonarhttp.request("HEAD", "/") response = sonarhttp.getresponse() ok_text("SonarQube em execucao no servidor {}.".format(url)) except Exception: error_text("SonarQube nao esta em execucao. Commit liberado.") system_exit_ok() def remove_file(file): """ Function to remove especific file. """ if os.path.isfile(file): os.remove(file) def remove_folder(folder): """ Function to remove especific folder. """ if os.path.isdir(folder): shutil.rmtree(folder) def verify_branch_is_merging(git_command): """ Function to verify branch is merging. """ branch_merging = git_command.execute("git status") if "All conflicts fixed but you are still merging." in branch_merging: ok_text(">> Commit de MERGE. SonarQube nao sera executado.") system_exit_ok() def find_systems_and_keys(repository): try: file = repository + "Configuracoes.ps1" command = ["powershell.exe", ". \"{}\";".format(file), "&obtemListaSolutionsDotNet | ConvertTo-Json"] output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) json_systems = json.loads(output.stdout) return json_systems except Exception: error_text("Nao foi possível encontrar os sistemas no arquivo Configuracoes.ps1.") system_exit_ok() def write_modules(modules_list, files, system): try: modules = [] modules_string = "" if system == "MSSNET": if len(modules_list) > 0: modules_list = sorted(modules_list) for module in modules_list: module_files = ",".join({file["File"].replace(module[1] + "/", "") for file in files if file["ID"] == system and module[1] in os.path.dirname(file["File"])}) if module_files != "": module_title = "WebServices" if "webservices" in module[0] else module[0].title() module_dict = { "Module": module_title, "BaseDir": "{}.sonar.projectBaseDir={}".format(module_title, module[1]), "Sources": "{}.sonar.sources={}".format(module_title, module_files) } modules.append(module_dict) modules_string = "sonar.modules=" + ",".join(sorted({module["Module"] for module in modules})) + "\n" for module in modules: modules_string += "\n" modules_string += module["BaseDir"] + "\n" modules_string += module["Sources"] + "\n" return modules_string except Exception as err: error_text("Nao foi possivel gerar os modulos do SonarQube.") system_exit_ok() def system_exit_block_commit(): sys.exit(1) def system_exit_ok(): sys.exit(0) def warning_text(text): print_("\033[93mWARNING - {}\033[0m\n".format(text)) def ok_text(text): print_("\033[92mOK - {}\033[0m\n".format(text)) def error_text(text): print_("\033[91mERROR - {}\033[0m\n".format(text))
krazybean/randomaas
refs/heads/master
tests/maintest.py
1
#!/usr/bin/env python import sys import os import unittest import urllib2 sys.path.insert(0,os.path.abspath(__file__+"/../..")) from app import main class TestMain(unittest.TestCase): def setUp(self): pass def test_randnum(self): m = main.randnum(6, 'num') self.assertTrue(bool(len(m) == 6)) # def test_response(self): # r = urllib2.urlopen('http://localhost:9003') # self.assertTrue(r.code == 200) if __name__=='__main__': unittest.main()
torrents-com/content
refs/heads/master
scrapy/torrents/remote/__init__.py
12133432
brittanystoroz/kitsune
refs/heads/master
kitsune/karma/templatetags/__init__.py
12133432
Kassaidre/python-training
refs/heads/master
generator/__init__.py
12133432
PXke/invenio
refs/heads/dev-pu
invenio/legacy/websearch/web/__init__.py
12133432
cuongthai/cuongthai-s-blog
refs/heads/master
django/conf/locale/mk/__init__.py
12133432
sublime1809/django
refs/heads/master
tests/custom_managers/__init__.py
12133432
erkrishna9/odoo
refs/heads/master
addons/hw_proxy/controllers/main.py
71
# -*- coding: utf-8 -*- import logging import commands import simplejson import os import os.path import openerp import time import random import subprocess import simplejson import werkzeug import werkzeug.wrappers _logger = logging.getLogger(__name__) from openerp import http from openerp.http import request # drivers modules must add to drivers an object with a get_status() method # so that 'status' can return the status of all active drivers drivers = {} class Proxy(http.Controller): def get_status(self): statuses = {} for driver in drivers: statuses[driver] = drivers[driver].get_status() return statuses @http.route('/hw_proxy/hello', type='http', auth='none', cors='*') def hello(self): return "ping" @http.route('/hw_proxy/handshake', type='json', auth='none', cors='*') def handshake(self): return True @http.route('/hw_proxy/status', type='http', auth='none', cors='*') def status_http(self): resp = """ <!DOCTYPE HTML> <html> <head> <title>Odoo's PosBox</title> <style> body { width: 480px; margin: 60px auto; font-family: sans-serif; text-align: justify; color: #6B6B6B; } .device { border-bottom: solid 1px rgb(216,216,216); padding: 9px; } .device:nth-child(2n) { background:rgb(240,240,240); } </style> </head> <body> <h1>Hardware Status</h1> <p>The list of enabled drivers and their status</p> """ statuses = self.get_status() for driver in statuses: status = statuses[driver] if status['status'] == 'connecting': color = 'black' elif status['status'] == 'connected': color = 'green' else: color = 'red' resp += "<h3 style='color:"+color+";'>"+driver+' : '+status['status']+"</h3>\n" resp += "<ul>\n" for msg in status['messages']: resp += '<li>'+msg+'</li>\n' resp += "</ul>\n" resp += """ <h2>Connected Devices</h2> <p>The list of connected USB devices as seen by the posbox</p> """ devices = commands.getoutput("lsusb").split('\n') resp += "<div class='devices'>\n" for device in devices: device_name = device[device.find('ID')+2:] resp+= "<div class='device' data-device='"+device+"'>"+device_name+"</div>\n" resp += "</div>\n" resp += """ <h2>Add New Printer</h2> <p> Copy and paste your printer's device description in the form below. You can find your printer's description in the device list above. If you find that your printer works well, please send your printer's description to <a href='mailto:support@openerp.com'> support@openerp.com</a> so that we can add it to the default list of supported devices. </p> <form action='/hw_proxy/escpos/add_supported_device' method='GET'> <input type='text' style='width:400px' name='device_string' placeholder='123a:b456 Sample Device description' /> <input type='submit' value='submit' /> </form> <h2>Reset To Defaults</h2> <p>If the added devices cause problems, you can <a href='/hw_proxy/escpos/reset_supported_devices'>Reset the device list to factory default.</a> This operation cannot be undone.</p> """ resp += "</body>\n</html>\n\n" return request.make_response(resp,{ 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', }) @http.route('/hw_proxy/status_json', type='json', auth='none', cors='*') def status_json(self): return self.get_status() @http.route('/hw_proxy/scan_item_success', type='json', auth='none', cors='*') def scan_item_success(self, ean): """ A product has been scanned with success """ print 'scan_item_success: ' + str(ean) @http.route('/hw_proxy/scan_item_error_unrecognized', type='json', auth='none', cors='*') def scan_item_error_unrecognized(self, ean): """ A product has been scanned without success """ print 'scan_item_error_unrecognized: ' + str(ean) @http.route('/hw_proxy/help_needed', type='json', auth='none', cors='*') def help_needed(self): """ The user wants an help (ex: light is on) """ print "help_needed" @http.route('/hw_proxy/help_canceled', type='json', auth='none', cors='*') def help_canceled(self): """ The user stops the help request """ print "help_canceled" @http.route('/hw_proxy/payment_request', type='json', auth='none', cors='*') def payment_request(self, price): """ The PoS will activate the method payment """ print "payment_request: price:"+str(price) return 'ok' @http.route('/hw_proxy/payment_status', type='json', auth='none', cors='*') def payment_status(self): print "payment_status" return { 'status':'waiting' } @http.route('/hw_proxy/payment_cancel', type='json', auth='none', cors='*') def payment_cancel(self): print "payment_cancel" @http.route('/hw_proxy/transaction_start', type='json', auth='none', cors='*') def transaction_start(self): print 'transaction_start' @http.route('/hw_proxy/transaction_end', type='json', auth='none', cors='*') def transaction_end(self): print 'transaction_end' @http.route('/hw_proxy/cashier_mode_activated', type='json', auth='none', cors='*') def cashier_mode_activated(self): print 'cashier_mode_activated' @http.route('/hw_proxy/cashier_mode_deactivated', type='json', auth='none', cors='*') def cashier_mode_deactivated(self): print 'cashier_mode_deactivated' @http.route('/hw_proxy/open_cashbox', type='json', auth='none', cors='*') def open_cashbox(self): print 'open_cashbox' @http.route('/hw_proxy/print_receipt', type='json', auth='none', cors='*') def print_receipt(self, receipt): print 'print_receipt' + str(receipt) @http.route('/hw_proxy/is_scanner_connected', type='json', auth='none', cors='*') def print_receipt(self, receipt): print 'is_scanner_connected?' return False @http.route('/hw_proxy/scanner', type='json', auth='none', cors='*') def print_receipt(self, receipt): print 'scanner' time.sleep(10) return '' @http.route('/hw_proxy/log', type='json', auth='none', cors='*') def log(self, arguments): _logger.info(' '.join(str(v) for v in arguments)) @http.route('/hw_proxy/print_pdf_invoice', type='json', auth='none', cors='*') def print_pdf_invoice(self, pdfinvoice): print 'print_pdf_invoice' + str(pdfinvoice)
pombredanne/http-repo.gem5.org-gem5-
refs/heads/master
tests/quick/se/50.memtest/test.py
90
# Copyright (c) 2006-2007 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Ron Dreslinski MemTest.max_loads=1e5 MemTest.progress_interval=1e4
mistercrunch/airflow
refs/heads/master
airflow/operators/sqlite_operator.py
7
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """This module is deprecated. Please use `airflow.providers.sqlite.operators.sqlite`.""" import warnings # pylint: disable=unused-import from airflow.providers.sqlite.operators.sqlite import SqliteOperator # noqa warnings.warn( "This module is deprecated. Please use `airflow.providers.sqlite.operators.sqlite`.", DeprecationWarning, stacklevel=2, )
epssy/hue
refs/heads/master
desktop/core/ext-py/thrift-0.9.1/src/transport/THttpClient.py
157
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 httplib import os import socket import sys import urllib import urlparse import warnings from cStringIO import StringIO from TTransport import * class THttpClient(TTransportBase): """Http implementation of TTransport base.""" def __init__(self, uri_or_host, port=None, path=None): """THttpClient supports two different types constructor parameters. THttpClient(host, port, path) - deprecated THttpClient(uri) Only the second supports https. """ if port is not None: warnings.warn( "Please use the THttpClient('http://host:port/path') syntax", DeprecationWarning, stacklevel=2) self.host = uri_or_host self.port = port assert path self.path = path self.scheme = 'http' else: parsed = urlparse.urlparse(uri_or_host) self.scheme = parsed.scheme assert self.scheme in ('http', 'https') if self.scheme == 'http': self.port = parsed.port or httplib.HTTP_PORT elif self.scheme == 'https': self.port = parsed.port or httplib.HTTPS_PORT self.host = parsed.hostname self.path = parsed.path if parsed.query: self.path += '?%s' % parsed.query self.__wbuf = StringIO() self.__http = None self.__timeout = None self.__custom_headers = None def open(self): if self.scheme == 'http': self.__http = httplib.HTTP(self.host, self.port) else: self.__http = httplib.HTTPS(self.host, self.port) def close(self): self.__http.close() self.__http = None def isOpen(self): return self.__http is not None def setTimeout(self, ms): if not hasattr(socket, 'getdefaulttimeout'): raise NotImplementedError if ms is None: self.__timeout = None else: self.__timeout = ms / 1000.0 def setCustomHeaders(self, headers): self.__custom_headers = headers def read(self, sz): return self.__http.file.read(sz) def write(self, buf): self.__wbuf.write(buf) def __withTimeout(f): def _f(*args, **kwargs): orig_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(args[0].__timeout) result = f(*args, **kwargs) socket.setdefaulttimeout(orig_timeout) return result return _f def flush(self): if self.isOpen(): self.close() self.open() # Pull data out of buffer data = self.__wbuf.getvalue() self.__wbuf = StringIO() # HTTP request self.__http.putrequest('POST', self.path) # Write headers self.__http.putheader('Host', self.host) self.__http.putheader('Content-Type', 'application/x-thrift') self.__http.putheader('Content-Length', str(len(data))) if not self.__custom_headers or 'User-Agent' not in self.__custom_headers: user_agent = 'Python/THttpClient' script = os.path.basename(sys.argv[0]) if script: user_agent = '%s (%s)' % (user_agent, urllib.quote(script)) self.__http.putheader('User-Agent', user_agent) if self.__custom_headers: for key, val in self.__custom_headers.iteritems(): self.__http.putheader(key, val) self.__http.endheaders() # Write payload self.__http.send(data) # Get reply to flush the request self.code, self.message, self.headers = self.__http.getreply() # Decorate if we know how to timeout if hasattr(socket, 'getdefaulttimeout'): flush = __withTimeout(flush)
infinigrove/SR700-Artisan-PDServer
refs/heads/master
cmds/Roaster_Set_Temp.py
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # SR700-Artisan-PDServer, released under GPLv3 # Roaster Set Temperature import Pyro4 import sys new_roaster_temperature = sys.argv[1] roast_control = Pyro4.Proxy("PYRONAME:roaster.sr700") if int(new_roaster_temperature) > -1 and int(new_roaster_temperature) <551: roast_control.set_temperature(new_roaster_temperature)
nrwahl2/ansible
refs/heads/devel
lib/ansible/module_utils/redhat.py
26
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c), James Laska # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import re import shutil import tempfile import types from ansible.module_utils.six.moves import configparser class RegistrationBase(object): def __init__(self, module, username=None, password=None): self.module = module self.username = username self.password = password def configure(self): raise NotImplementedError("Must be implemented by a sub-class") def enable(self): # Remove any existing redhat.repo redhat_repo = '/etc/yum.repos.d/redhat.repo' if os.path.isfile(redhat_repo): os.unlink(redhat_repo) def register(self): raise NotImplementedError("Must be implemented by a sub-class") def unregister(self): raise NotImplementedError("Must be implemented by a sub-class") def unsubscribe(self): raise NotImplementedError("Must be implemented by a sub-class") def update_plugin_conf(self, plugin, enabled=True): plugin_conf = '/etc/yum/pluginconf.d/%s.conf' % plugin if os.path.isfile(plugin_conf): tmpfd, tmpfile = tempfile.mkstemp() shutil.copy2(plugin_conf, tmpfile) cfg = configparser.ConfigParser() cfg.read([tmpfile]) if enabled: cfg.set('main', 'enabled', 1) else: cfg.set('main', 'enabled', 0) fd = open(tmpfile, 'w+') cfg.write(fd) fd.close() self.module.atomic_move(tmpfile, plugin_conf) def subscribe(self, **kwargs): raise NotImplementedError("Must be implemented by a sub-class") class Rhsm(RegistrationBase): def __init__(self, module, username=None, password=None): RegistrationBase.__init__(self, module, username, password) self.config = self._read_config() self.module = module def _read_config(self, rhsm_conf='/etc/rhsm/rhsm.conf'): ''' Load RHSM configuration from /etc/rhsm/rhsm.conf. Returns: * ConfigParser object ''' # Read RHSM defaults ... cp = configparser.ConfigParser() cp.read(rhsm_conf) # Add support for specifying a default value w/o having to standup some configuration # Yeah, I know this should be subclassed ... but, oh well def get_option_default(self, key, default=''): sect, opt = key.split('.', 1) if self.has_section(sect) and self.has_option(sect, opt): return self.get(sect, opt) else: return default cp.get_option = types.MethodType(get_option_default, cp, configparser.ConfigParser) return cp def enable(self): ''' Enable the system to receive updates from subscription-manager. This involves updating affected yum plugins and removing any conflicting yum repositories. ''' RegistrationBase.enable(self) self.update_plugin_conf('rhnplugin', False) self.update_plugin_conf('subscription-manager', True) def configure(self, **kwargs): ''' Configure the system as directed for registration with RHN Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'config'] # Pass supplied **kwargs as parameters to subscription-manager. Ignore # non-configuration parameters and replace '_' with '.'. For example, # 'server_hostname' becomes '--system.hostname'. for k, v in kwargs.items(): if re.search(r'^(system|rhsm)_', k): args.append('--%s=%s' % (k.replace('_', '.'), v)) self.module.run_command(args, check_rc=True) @property def is_registered(self): ''' Determine whether the current system Returns: * Boolean - whether the current system is currently registered to RHN. ''' # Quick version... if False: return os.path.isfile('/etc/pki/consumer/cert.pem') and \ os.path.isfile('/etc/pki/consumer/key.pem') args = ['subscription-manager', 'identity'] rc, stdout, stderr = self.module.run_command(args, check_rc=False) if rc == 0: return True else: return False def register(self, username, password, autosubscribe, activationkey): ''' Register the current system to the provided RHN server Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'register'] # Generate command arguments if activationkey: args.append('--activationkey "%s"' % activationkey) else: if autosubscribe: args.append('--autosubscribe') if username: args.extend(['--username', username]) if password: args.extend(['--password', password]) # Do the needful... rc, stderr, stdout = self.module.run_command(args, check_rc=True) def unsubscribe(self): ''' Unsubscribe a system from all subscribed channels Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'unsubscribe', '--all'] rc, stderr, stdout = self.module.run_command(args, check_rc=True) def unregister(self): ''' Unregister a currently registered system Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'unregister'] rc, stderr, stdout = self.module.run_command(args, check_rc=True) self.update_plugin_conf('rhnplugin', False) self.update_plugin_conf('subscription-manager', False) def subscribe(self, regexp): ''' Subscribe current system to available pools matching the specified regular expression Raises: * Exception - if error occurs while running command ''' # Available pools ready for subscription available_pools = RhsmPools(self.module) for pool in available_pools.filter(regexp): pool.subscribe() class RhsmPool(object): ''' Convenience class for housing subscription information ''' def __init__(self, module, **kwargs): self.module = module for k, v in kwargs.items(): setattr(self, k, v) def __str__(self): return str(self.__getattribute__('_name')) def subscribe(self): args = "subscription-manager subscribe --pool %s" % self.PoolId rc, stdout, stderr = self.module.run_command(args, check_rc=True) if rc == 0: return True else: return False class RhsmPools(object): """ This class is used for manipulating pools subscriptions with RHSM """ def __init__(self, module): self.module = module self.products = self._load_product_list() def __iter__(self): return self.products.__iter__() def _load_product_list(self): """ Loads list of all available pools for system in data structure """ args = "subscription-manager list --available" rc, stdout, stderr = self.module.run_command(args, check_rc=True) products = [] for line in stdout.split('\n'): # Remove leading+trailing whitespace line = line.strip() # An empty line implies the end of an output group if len(line) == 0: continue # If a colon ':' is found, parse elif ':' in line: (key, value) = line.split(':', 1) key = key.strip().replace(" ", "") # To unify value = value.strip() if key in ['ProductName', 'SubscriptionName']: # Remember the name for later processing products.append(RhsmPool(self.module, _name=value, key=value)) elif products: # Associate value with most recently recorded product products[-1].__setattr__(key, value) # FIXME - log some warning? # else: # warnings.warn("Unhandled subscription key/value: %s/%s" % (key,value)) return products def filter(self, regexp='^$'): ''' Return a list of RhsmPools whose name matches the provided regular expression ''' r = re.compile(regexp) for product in self.products: if r.search(product._name): yield product
BigRoy/pyblish-magenta
refs/heads/master
run_testsuite.py
3
import os import sys import logging import nose # Expose Pyblish Magenta to PYTHONPATH path = os.path.dirname(__file__) sys.path.insert(0, path) # Plug-ins produce a lot of messages, # mute these during tests. logging.disable(logging.CRITICAL) if "maya" in sys.executable.lower(): __import__("pyblish_maya").setup() elif "houdini" in sys.executable.lower(): __import__("pyblish_houdini").setup() elif "nuke" in sys.executable.lower(): __import__("pyblish_nuke").setup() if __name__ == "__main__": argv = sys.argv[:] argv.extend(['--exclude=vendor', '--verbose']) nose.main(argv=argv) os._exit(0)
kailIII/geraldo
refs/heads/master
testproject/urls.py
11
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^testproject/', include('testproject.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), )
ukch/refugeedata
refs/heads/master
refugeedata/migrations/0007_auto_20150921_1725.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuidfield.fields import refugeedata.models class Migration(migrations.Migration): dependencies = [ ('refugeedata', '0006_auto_20150919_1917'), ] operations = [ migrations.AddField( model_name='registrationnumber', name='short_id_missing', field=models.BooleanField(default=False, verbose_name='short ID missing'), ), migrations.AlterField( model_name='registrationnumber', name='id', field=uuidfield.fields.UUIDField(primary_key=True, default=refugeedata.models.manual_uuid_generation, serialize=False, editable=False, max_length=32, blank=True, unique=True, verbose_name='ID'), ), ]
HalCanary/skia-hc
refs/heads/master
tools/skp/page_sets/skia_slashdot_mobile.py
8
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaMobilePage(page_module.Page): def __init__(self, url, page_set): super(SkiaMobilePage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedMobilePageState) self.archive_data_file = 'data/skia_slashdot_mobile.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaSlashdotMobilePageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaSlashdotMobilePageSet, self).__init__( archive_data_file='data/skia_slashdot_mobile.json') urls_list = [ # go/skia-skps-3-2019 'http://slashdot.org', ] for url in urls_list: self.AddStory(SkiaMobilePage(url, self))
jeroanan/Nes2
refs/heads/master
Tests/Test6502.py
1
import unittest from unittest.mock import Mock from Chip import OpCodeDefinitions from Chip.Chip6502 import Chip6502 from Chip.OpCodeFactory import OpCodeFactory from Chip.OpCodes.OraCommand import OraCommand class Test6502(unittest.TestCase): def test_execute_command_executes_opcode_factory_get_command(self): factory = Mock(OpCodeFactory) chip = Chip6502() chip.set_opcode_factory(factory) chip.execute(0x13) self.assertTrue(factory.get_command.called) def setUp(self): factory = Mock(OpCodeFactory) self.__target = Mock(OraCommand) factory.get_command.return_value = self.__target self.__chip = Chip6502() self.__chip.set_opcode_factory(factory) def test_execute_ora_immediate_opcode_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_immediate_command) def test_execute_ora_indirect_x_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_indirect_x_command) def test_execute_ora_zero_page_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_zero_page_command) def test_execute_ora_absolute_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_absolute_command) def test_execute_ora_indirect_y_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_indirect_y_command) def test_execute_ora_zero_page_x_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_zero_page_x_command) def test_execute_ora_absolute_y_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_absolute_y_command) def test_execute_ora_ora_absolute_x_command_executes_ora_command(self): self.__assert_opcode_calls_command(OpCodeDefinitions.ora_absolute_x_command) def __assert_opcode_calls_command(self, opcode): self.__chip.execute(opcode) self.assertTrue(self.__target.execute.called)
ake-koomsin/mapnik_nvpr
refs/heads/master
utils/pgsql2sqlite/build.py
2
# # This file is part of Mapnik (c++ mapping toolkit) # # Copyright (C) 2009 Artem Pavlenko, Dane Springmeyer # # Mapnik 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 2.1 of the License, or (at your option) any later version. # # This library 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 this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # import os from copy import copy Import ('env') prefix = env['PREFIX'] program_env = env.Clone() source = Split( """ main.cpp sqlite.cpp """ ) program_env['CXXFLAGS'] = copy(env['LIBMAPNIK_CXXFLAGS']) if env['HAS_CAIRO']: program_env.PrependUnique(CPPPATH=env['CAIROMM_CPPPATHS']) program_env.Append(CXXFLAGS = '-DHAVE_CAIRO') program_env.PrependUnique(CPPPATH=['#plugins/input/postgis']) libraries = [] boost_program_options = 'boost_program_options%s' % env['BOOST_APPEND'] libraries.extend([boost_program_options,'sqlite3','pq','mapnik','icuuc']) if env.get('BOOST_LIB_VERSION_FROM_HEADER'): boost_version_from_header = int(env['BOOST_LIB_VERSION_FROM_HEADER'].split('_')[1]) if boost_version_from_header >= 50: boost_system = 'boost_system%s' % env['BOOST_APPEND'] libraries.extend([boost_system]) linkflags = env['CUSTOM_LDFLAGS'] if env['SQLITE_LINKFLAGS']: linkflags.append(env['SQLITE_LINKFLAGS']) if env['RUNTIME_LINK'] == 'static': libraries.extend(['ldap','pam','ssl','crypto','krb5']) pgsql2sqlite = program_env.Program('pgsql2sqlite', source, LIBS=libraries, LINKFLAGS=linkflags) Depends(pgsql2sqlite, env.subst('../../src/%s' % env['MAPNIK_LIB_NAME'])) if 'uninstall' not in COMMAND_LINE_TARGETS: env.Install(os.path.join(env['INSTALL_PREFIX'],'bin'), pgsql2sqlite) env.Alias('install', os.path.join(env['INSTALL_PREFIX'],'bin')) env['create_uninstall_target'](env, os.path.join(env['INSTALL_PREFIX'],'bin','pgsql2sqlite'))
vikatory/kbengine
refs/heads/master
kbe/res/scripts/common/Lib/test/test_curses.py
67
# # Test script for the curses module # # This script doesn't actually display anything very coherent. but it # does call every method and function. # # Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(), # init_color() # Only called, not tested: getmouse(), ungetmouse() # import sys, tempfile, os # Optionally test curses module. This currently requires that the # 'curses' resource be given on the regrtest command line using the -u # option. If not available, nothing after this line will be executed. import unittest from test.support import requires, import_module import inspect requires('curses') # If either of these don't exist, skip the tests. curses = import_module('curses') curses.panel = import_module('curses.panel') # XXX: if newterm was supported we could use it instead of initscr and not exit term = os.environ.get('TERM') if not term or term == 'unknown': raise unittest.SkipTest("$TERM=%r, calling initscr() may cause exit" % term) if sys.platform == "cygwin": raise unittest.SkipTest("cygwin's curses mostly just hangs") def window_funcs(stdscr): "Test the methods of windows" win = curses.newwin(10,10) win = curses.newwin(5,5, 5,5) win2 = curses.newwin(15,15, 5,5) for meth in [stdscr.addch, stdscr.addstr]: for args in [('a'), ('a', curses.A_BOLD), (4,4, 'a'), (5,5, 'a', curses.A_BOLD)]: meth(*args) for meth in [stdscr.box, stdscr.clear, stdscr.clrtobot, stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch, stdscr.deleteln, stdscr.erase, stdscr.getbegyx, stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx, stdscr.getparyx, stdscr.getyx, stdscr.inch, stdscr.insertln, stdscr.instr, stdscr.is_wintouched, win.noutrefresh, stdscr.redrawwin, stdscr.refresh, stdscr.standout, stdscr.standend, stdscr.syncdown, stdscr.syncup, stdscr.touchwin, stdscr.untouchwin]: meth() stdscr.addnstr('1234', 3) stdscr.addnstr('1234', 3, curses.A_BOLD) stdscr.addnstr(4,4, '1234', 3) stdscr.addnstr(5,5, '1234', 3, curses.A_BOLD) stdscr.attron(curses.A_BOLD) stdscr.attroff(curses.A_BOLD) stdscr.attrset(curses.A_BOLD) stdscr.bkgd(' ') stdscr.bkgd(' ', curses.A_REVERSE) stdscr.bkgdset(' ') stdscr.bkgdset(' ', curses.A_REVERSE) win.border(65, 66, 67, 68, 69, 70, 71, 72) win.border('|', '!', '-', '_', '+', '\\', '#', '/') try: win.border(65, 66, 67, 68, 69, [], 71, 72) except TypeError: pass else: raise RuntimeError("Expected win.border() to raise TypeError") stdscr.clearok(1) win4 = stdscr.derwin(2,2) win4 = stdscr.derwin(1,1, 5,5) win4.mvderwin(9,9) stdscr.echochar('a') stdscr.echochar('a', curses.A_BOLD) stdscr.hline('-', 5) stdscr.hline('-', 5, curses.A_BOLD) stdscr.hline(1,1,'-', 5) stdscr.hline(1,1,'-', 5, curses.A_BOLD) stdscr.idcok(1) stdscr.idlok(1) stdscr.immedok(1) stdscr.insch('c') stdscr.insdelln(1) stdscr.insnstr('abc', 3) stdscr.insnstr('abc', 3, curses.A_BOLD) stdscr.insnstr(5, 5, 'abc', 3) stdscr.insnstr(5, 5, 'abc', 3, curses.A_BOLD) stdscr.insstr('def') stdscr.insstr('def', curses.A_BOLD) stdscr.insstr(5, 5, 'def') stdscr.insstr(5, 5, 'def', curses.A_BOLD) stdscr.is_linetouched(0) stdscr.keypad(1) stdscr.leaveok(1) stdscr.move(3,3) win.mvwin(2,2) stdscr.nodelay(1) stdscr.notimeout(1) win2.overlay(win) win2.overwrite(win) win2.overlay(win, 1, 2, 2, 1, 3, 3) win2.overwrite(win, 1, 2, 2, 1, 3, 3) stdscr.redrawln(1,2) stdscr.scrollok(1) stdscr.scroll() stdscr.scroll(2) stdscr.scroll(-3) stdscr.move(12, 2) stdscr.setscrreg(10,15) win3 = stdscr.subwin(10,10) win3 = stdscr.subwin(10,10, 5,5) stdscr.syncok(1) stdscr.timeout(5) stdscr.touchline(5,5) stdscr.touchline(5,5,0) stdscr.vline('a', 3) stdscr.vline('a', 3, curses.A_STANDOUT) stdscr.chgat(5, 2, 3, curses.A_BLINK) stdscr.chgat(3, curses.A_BOLD) stdscr.chgat(5, 8, curses.A_UNDERLINE) stdscr.chgat(curses.A_BLINK) stdscr.refresh() stdscr.vline(1,1, 'a', 3) stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT) if hasattr(curses, 'resize'): stdscr.resize() if hasattr(curses, 'enclose'): stdscr.enclose() def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() # Functions that actually need arguments if curses.tigetstr("cnorm"): curses.curs_set(1) curses.delay_output(1) curses.echo() ; curses.echo(1) f = tempfile.TemporaryFile() stdscr.putwin(f) f.seek(0) curses.getwin(f) f.close() curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50,50) win = curses.newwin(5,5) win = curses.newwin(5,5, 1,1) curses.nl() ; curses.nl(1) curses.putp(b'abc') curses.qiflush() curses.raw() ; curses.raw(1) curses.setsyx(5,5) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm(b'cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1) # Functions only available on a few platforms if curses.has_colors(): curses.start_color() curses.init_pair(2, 1,1) curses.color_content(1) curses.color_pair(2) curses.pair_content(curses.COLOR_PAIRS - 1) curses.pair_number(0) if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'keyname'): curses.keyname(13) if hasattr(curses, 'has_key'): curses.has_key(13) if hasattr(curses, 'getmouse'): (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED) # availmask indicates that mouse stuff not available. if availmask != 0: curses.mouseinterval(10) # just verify these don't cause errors curses.ungetmouse(0, 0, 0, 0, curses.BUTTON1_PRESSED) m = curses.getmouse() if hasattr(curses, 'is_term_resized'): curses.is_term_resized(*stdscr.getmaxyx()) if hasattr(curses, 'resizeterm'): curses.resizeterm(*stdscr.getmaxyx()) if hasattr(curses, 'resize_term'): curses.resize_term(*stdscr.getmaxyx()) def unit_tests(): from curses import ascii for ch, expected in [('a', 'a'), ('A', 'A'), (';', ';'), (' ', ' '), ('\x7f', '^?'), ('\n', '^J'), ('\0', '^@'), # Meta-bit characters ('\x8a', '!^J'), ('\xc1', '!A'), ]: if ascii.unctrl(ch) != expected: print('curses.unctrl fails on character', repr(ch)) def test_userptr_without_set(stdscr): w = curses.newwin(10, 10) p = curses.panel.new_panel(w) # try to access userptr() before calling set_userptr() -- segfaults try: p.userptr() raise RuntimeError('userptr should fail since not set') except curses.panel.error: pass def test_userptr_memory_leak(stdscr): w = curses.newwin(10, 10) p = curses.panel.new_panel(w) obj = object() nrefs = sys.getrefcount(obj) for i in range(100): p.set_userptr(obj) p.set_userptr(None) if sys.getrefcount(obj) != nrefs: raise RuntimeError("set_userptr leaked references") def test_userptr_segfault(stdscr): panel = curses.panel.new_panel(stdscr) class A: def __del__(self): panel.set_userptr(None) panel.set_userptr(A()) panel.set_userptr(None) def test_resize_term(stdscr): if hasattr(curses, 'resizeterm'): lines, cols = curses.LINES, curses.COLS curses.resizeterm(lines - 1, cols + 1) if curses.LINES != lines - 1 or curses.COLS != cols + 1: raise RuntimeError("Expected resizeterm to update LINES and COLS") def test_issue6243(stdscr): curses.ungetch(1025) stdscr.getkey() def test_unget_wch(stdscr): if not hasattr(curses, 'unget_wch'): return encoding = stdscr.encoding for ch in ('a', '\xe9', '\u20ac', '\U0010FFFF'): try: ch.encode(encoding) except UnicodeEncodeError: continue try: curses.unget_wch(ch) except Exception as err: raise Exception("unget_wch(%a) failed with encoding %s: %s" % (ch, stdscr.encoding, err)) read = stdscr.get_wch() if read != ch: raise AssertionError("%r != %r" % (read, ch)) code = ord(ch) curses.unget_wch(code) read = stdscr.get_wch() if read != ch: raise AssertionError("%r != %r" % (read, ch)) def test_issue10570(): b = curses.tparm(curses.tigetstr("cup"), 5, 3) assert type(b) is bytes curses.putp(b) def test_encoding(stdscr): import codecs encoding = stdscr.encoding codecs.lookup(encoding) try: stdscr.encoding = 10 except TypeError: pass else: raise AssertionError("TypeError not raised") stdscr.encoding = encoding try: del stdscr.encoding except TypeError: pass else: raise AssertionError("TypeError not raised") def test_issue21088(stdscr): # # http://bugs.python.org/issue21088 # # the bug: # when converting curses.window.addch to Argument Clinic # the first two parameters were switched. # if someday we can represent the signature of addch # we will need to rewrite this test. try: signature = inspect.signature(stdscr.addch) self.assertFalse(signature) except ValueError: # not generating a signature is fine. pass # So. No signature for addch. # But Argument Clinic gave us a human-readable equivalent # as the first line of the docstring. So we parse that, # and ensure that the parameters appear in the correct order. # Since this is parsing output from Argument Clinic, we can # be reasonably certain the generated parsing code will be # correct too. human_readable_signature = stdscr.addch.__doc__.split("\n")[0] offset = human_readable_signature.find("[y, x,]") assert offset >= 0, "" def main(stdscr): curses.savetty() try: module_funcs(stdscr) window_funcs(stdscr) test_userptr_without_set(stdscr) test_userptr_memory_leak(stdscr) test_userptr_segfault(stdscr) test_resize_term(stdscr) test_issue6243(stdscr) test_unget_wch(stdscr) test_issue10570() test_encoding(stdscr) test_issue21088(stdscr) finally: curses.resetty() def test_main(): if not sys.__stdout__.isatty(): raise unittest.SkipTest("sys.__stdout__ is not a tty") # testing setupterm() inside initscr/endwin # causes terminal breakage curses.setupterm(fd=sys.__stdout__.fileno()) try: stdscr = curses.initscr() main(stdscr) finally: curses.endwin() unit_tests() if __name__ == '__main__': curses.wrapper(main) unit_tests()
adoosii/edx-platform
refs/heads/master
lms/djangoapps/instructor/tests/test_api.py
13
# -*- coding: utf-8 -*- """ Unit tests for instructor.api methods. """ import datetime import ddt import functools import random import pytz import io import json import requests import shutil import tempfile from urllib import quote from django.conf import settings from django.contrib.auth.models import User from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.core.urlresolvers import reverse from django.http import HttpRequest, HttpResponse from django.test import RequestFactory, TestCase from django.test.utils import override_settings from django.utils.timezone import utc from django.utils.translation import ugettext as _ from mock import Mock, patch from nose.tools import raises from nose.plugins.attrib import attr from opaque_keys.edx.locations import SlashSeparatedCourseKey from opaque_keys.edx.locator import UsageKey from course_modes.models import CourseMode from courseware.models import StudentModule from courseware.tests.factories import StaffFactory, InstructorFactory, BetaTesterFactory, UserProfileFactory from courseware.tests.helpers import LoginEnrollmentTestCase from django_comment_common.models import FORUM_ROLE_COMMUNITY_TA from django_comment_common.utils import seed_permissions_roles from microsite_configuration import microsite from shoppingcart.models import ( RegistrationCodeRedemption, Order, CouponRedemption, PaidCourseRegistration, Coupon, Invoice, CourseRegistrationCode, CourseRegistrationCodeInvoiceItem, InvoiceTransaction) from shoppingcart.pdf import PDFInvoice from student.models import ( CourseEnrollment, CourseEnrollmentAllowed, NonExistentCourseError, ManualEnrollmentAudit, UNENROLLED_TO_ENROLLED, ENROLLED_TO_UNENROLLED, ALLOWEDTOENROLL_TO_UNENROLLED, ENROLLED_TO_ENROLLED, UNENROLLED_TO_ALLOWEDTOENROLL, UNENROLLED_TO_UNENROLLED, ALLOWEDTOENROLL_TO_ENROLLED ) from student.tests.factories import UserFactory, CourseModeFactory, AdminFactory from student.roles import CourseBetaTesterRole, CourseSalesAdminRole, CourseFinanceAdminRole, CourseInstructorRole from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from xmodule.fields import Date from courseware.models import StudentFieldOverride import instructor_task.api import instructor.views.api from instructor.views.api import require_finance_admin from instructor.tests.utils import FakeContentTask, FakeEmail, FakeEmailInfo from instructor.views.api import _split_input_list, common_exceptions_400, generate_unique_password from instructor_task.api_helper import AlreadyRunningError from certificates.tests.factories import GeneratedCertificateFactory from certificates.models import CertificateStatuses from openedx.core.djangoapps.course_groups.cohorts import set_course_cohort_settings from .test_tools import msk_from_problem_urlname DATE_FIELD = Date() EXPECTED_CSV_HEADER = ( '"code","redeem_code_url","course_id","company_name","created_by","redeemed_by","invoice_id","purchaser",' '"customer_reference_number","internal_reference"' ) EXPECTED_COUPON_CSV_HEADER = '"Coupon Code","Course Id","% Discount","Description","Expiration Date",' \ '"Is Active","Code Redeemed Count","Total Discounted Seats","Total Discounted Amount"' # ddt data for test cases involving reports REPORTS_DATA = ( { 'report_type': 'grade', 'instructor_api_endpoint': 'calculate_grades_csv', 'task_api_endpoint': 'instructor_task.api.submit_calculate_grades_csv', 'extra_instructor_api_kwargs': {} }, { 'report_type': 'enrolled learner profile', 'instructor_api_endpoint': 'get_students_features', 'task_api_endpoint': 'instructor_task.api.submit_calculate_students_features_csv', 'extra_instructor_api_kwargs': {'csv': '/csv'} }, { 'report_type': 'detailed enrollment', 'instructor_api_endpoint': 'get_enrollment_report', 'task_api_endpoint': 'instructor_task.api.submit_detailed_enrollment_features_csv', 'extra_instructor_api_kwargs': {} }, { 'report_type': 'enrollment', 'instructor_api_endpoint': 'get_students_who_may_enroll', 'task_api_endpoint': 'instructor_task.api.submit_calculate_may_enroll_csv', 'extra_instructor_api_kwargs': {}, }, { 'report_type': 'proctored exam results', 'instructor_api_endpoint': 'get_proctored_exam_results', 'task_api_endpoint': 'instructor_task.api.submit_proctored_exam_results_report', 'extra_instructor_api_kwargs': {}, }, { 'report_type': 'problem responses', 'instructor_api_endpoint': 'get_problem_responses', 'task_api_endpoint': 'instructor_task.api.submit_calculate_problem_responses_csv', 'extra_instructor_api_kwargs': {}, } ) # ddt data for test cases involving executive summary report EXECUTIVE_SUMMARY_DATA = ( { 'report_type': 'executive summary', 'instructor_api_endpoint': 'get_exec_summary_report', 'task_api_endpoint': 'instructor_task.api.submit_executive_summary_report', 'extra_instructor_api_kwargs': {} }, ) @common_exceptions_400 def view_success(request): # pylint: disable=unused-argument "A dummy view for testing that returns a simple HTTP response" return HttpResponse('success') @common_exceptions_400 def view_user_doesnotexist(request): # pylint: disable=unused-argument "A dummy view that raises a User.DoesNotExist exception" raise User.DoesNotExist() @common_exceptions_400 def view_alreadyrunningerror(request): # pylint: disable=unused-argument "A dummy view that raises an AlreadyRunningError exception" raise AlreadyRunningError() @attr('shard_1') class TestCommonExceptions400(TestCase): """ Testing the common_exceptions_400 decorator. """ def setUp(self): super(TestCommonExceptions400, self).setUp() self.request = Mock(spec=HttpRequest) self.request.META = {} def test_happy_path(self): resp = view_success(self.request) self.assertEqual(resp.status_code, 200) def test_user_doesnotexist(self): self.request.is_ajax.return_value = False resp = view_user_doesnotexist(self.request) # pylint: disable=assignment-from-no-return self.assertEqual(resp.status_code, 400) self.assertIn("User does not exist", resp.content) def test_user_doesnotexist_ajax(self): self.request.is_ajax.return_value = True resp = view_user_doesnotexist(self.request) # pylint: disable=assignment-from-no-return self.assertEqual(resp.status_code, 400) result = json.loads(resp.content) self.assertIn("User does not exist", result["error"]) def test_alreadyrunningerror(self): self.request.is_ajax.return_value = False resp = view_alreadyrunningerror(self.request) # pylint: disable=assignment-from-no-return self.assertEqual(resp.status_code, 400) self.assertIn("Task is already running", resp.content) def test_alreadyrunningerror_ajax(self): self.request.is_ajax.return_value = True resp = view_alreadyrunningerror(self.request) # pylint: disable=assignment-from-no-return self.assertEqual(resp.status_code, 400) result = json.loads(resp.content) self.assertIn("Task is already running", result["error"]) @attr('shard_1') @patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message')) @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False}) class TestInstructorAPIDenyLevels(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Ensure that users cannot access endpoints they shouldn't be able to. """ @classmethod def setUpClass(cls): super(TestInstructorAPIDenyLevels, cls).setUpClass() cls.course = CourseFactory.create() cls.problem_location = msk_from_problem_urlname( cls.course.id, 'robot-some-problem-urlname' ) cls.problem_urlname = cls.problem_location.to_deprecated_string() def setUp(self): super(TestInstructorAPIDenyLevels, self).setUp() self.user = UserFactory.create() CourseEnrollment.enroll(self.user, self.course.id) _module = StudentModule.objects.create( student=self.user, course_id=self.course.id, module_state_key=self.problem_location, state=json.dumps({'attempts': 10}), ) # Endpoints that only Staff or Instructors can access self.staff_level_endpoints = [ ('students_update_enrollment', {'identifiers': 'foo@example.org', 'action': 'enroll'}), ('get_grading_config', {}), ('get_students_features', {}), ('get_student_progress_url', {'unique_student_identifier': self.user.username}), ('reset_student_attempts', {'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.user.email}), ('update_forum_role_membership', {'unique_student_identifier': self.user.email, 'rolename': 'Moderator', 'action': 'allow'}), ('list_forum_members', {'rolename': FORUM_ROLE_COMMUNITY_TA}), ('send_email', {'send_to': 'staff', 'subject': 'test', 'message': 'asdf'}), ('list_instructor_tasks', {}), ('list_background_email_tasks', {}), ('list_report_downloads', {}), ('list_financial_report_downloads', {}), ('calculate_grades_csv', {}), ('get_students_features', {}), ('get_enrollment_report', {}), ('get_students_who_may_enroll', {}), ('get_exec_summary_report', {}), ('get_proctored_exam_results', {}), ('get_problem_responses', {}), ] # Endpoints that only Instructors can access self.instructor_level_endpoints = [ ('bulk_beta_modify_access', {'identifiers': 'foo@example.org', 'action': 'add'}), ('modify_access', {'unique_student_identifier': self.user.email, 'rolename': 'beta', 'action': 'allow'}), ('list_course_role_members', {'rolename': 'beta'}), ('rescore_problem', {'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.user.email}), ] def _access_endpoint(self, endpoint, args, status_code, msg): """ Asserts that accessing the given `endpoint` gets a response of `status_code`. endpoint: string, endpoint for instructor dash API args: dict, kwargs for `reverse` call status_code: expected HTTP status code response msg: message to display if assertion fails. """ url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()}) if endpoint in ['send_email', 'students_update_enrollment', 'bulk_beta_modify_access']: response = self.client.post(url, args) else: response = self.client.get(url, args) self.assertEqual( response.status_code, status_code, msg=msg ) def test_student_level(self): """ Ensure that an enrolled student can't access staff or instructor endpoints. """ self.client.login(username=self.user.username, password='test') for endpoint, args in self.staff_level_endpoints: self._access_endpoint( endpoint, args, 403, "Student should not be allowed to access endpoint " + endpoint ) for endpoint, args in self.instructor_level_endpoints: self._access_endpoint( endpoint, args, 403, "Student should not be allowed to access endpoint " + endpoint ) def _access_problem_responses_endpoint(self, msg): """ Access endpoint for problem responses report, ensuring that UsageKey.from_string returns a problem key that the endpoint can work with. msg: message to display if assertion fails. """ mock_problem_key = Mock(return_value=u'') mock_problem_key.course_key = self.course.id with patch.object(UsageKey, 'from_string') as patched_method: patched_method.return_value = mock_problem_key self._access_endpoint('get_problem_responses', {}, 200, msg) def test_staff_level(self): """ Ensure that a staff member can't access instructor endpoints. """ staff_member = StaffFactory(course_key=self.course.id) CourseEnrollment.enroll(staff_member, self.course.id) CourseFinanceAdminRole(self.course.id).add_users(staff_member) self.client.login(username=staff_member.username, password='test') # Try to promote to forums admin - not working # update_forum_role(self.course.id, staff_member, FORUM_ROLE_ADMINISTRATOR, 'allow') for endpoint, args in self.staff_level_endpoints: # TODO: make these work if endpoint in ['update_forum_role_membership', 'list_forum_members']: continue elif endpoint == 'get_problem_responses': self._access_problem_responses_endpoint( "Staff member should be allowed to access endpoint " + endpoint ) continue self._access_endpoint( endpoint, args, 200, "Staff member should be allowed to access endpoint " + endpoint ) for endpoint, args in self.instructor_level_endpoints: self._access_endpoint( endpoint, args, 403, "Staff member should not be allowed to access endpoint " + endpoint ) def test_instructor_level(self): """ Ensure that an instructor member can access all endpoints. """ inst = InstructorFactory(course_key=self.course.id) CourseEnrollment.enroll(inst, self.course.id) CourseFinanceAdminRole(self.course.id).add_users(inst) self.client.login(username=inst.username, password='test') for endpoint, args in self.staff_level_endpoints: # TODO: make these work if endpoint in ['update_forum_role_membership']: continue elif endpoint == 'get_problem_responses': self._access_problem_responses_endpoint( "Instructor should be allowed to access endpoint " + endpoint ) continue self._access_endpoint( endpoint, args, 200, "Instructor should be allowed to access endpoint " + endpoint ) for endpoint, args in self.instructor_level_endpoints: # TODO: make this work if endpoint in ['rescore_problem']: continue self._access_endpoint( endpoint, args, 200, "Instructor should be allowed to access endpoint " + endpoint ) @attr('shard_1') @patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': True}) class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test Bulk account creation and enrollment from csv file """ @classmethod def setUpClass(cls): super(TestInstructorAPIBulkAccountCreationAndEnrollment, cls).setUpClass() cls.course = CourseFactory.create() cls.url = reverse('register_and_enroll_students', kwargs={'course_id': cls.course.id.to_deprecated_string()}) def setUp(self): super(TestInstructorAPIBulkAccountCreationAndEnrollment, self).setUp() self.request = RequestFactory().request() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.not_enrolled_student = UserFactory( username='NotEnrolledStudent', email='nonenrolled@test.com', first_name='NotEnrolled', last_name='Student' ) @patch('instructor.views.api.log.info') def test_account_creation_and_enrollment_with_csv(self, info_log): """ Happy path test to create a single new user """ csv_content = "test_student@example.com,test_student_1,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertEquals(len(data['row_errors']), 0) self.assertEquals(len(data['warnings']), 0) self.assertEquals(len(data['general_errors']), 0) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) # test the log for email that's send to new created user. info_log.assert_called_with('email sent to new created user at %s', 'test_student@example.com') @patch('instructor.views.api.log.info') def test_account_creation_and_enrollment_with_csv_with_blank_lines(self, info_log): """ Happy path test to create a single new user """ csv_content = "\ntest_student@example.com,test_student_1,tester1,USA\n\n" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertEquals(len(data['row_errors']), 0) self.assertEquals(len(data['warnings']), 0) self.assertEquals(len(data['general_errors']), 0) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) # test the log for email that's send to new created user. info_log.assert_called_with('email sent to new created user at %s', 'test_student@example.com') @patch('instructor.views.api.log.info') def test_email_and_username_already_exist(self, info_log): """ If the email address and username already exists and the user is enrolled in the course, do nothing (including no email gets sent out) """ csv_content = "test_student@example.com,test_student_1,tester1,USA\n" \ "test_student@example.com,test_student_1,tester2,US" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertEquals(len(data['row_errors']), 0) self.assertEquals(len(data['warnings']), 0) self.assertEquals(len(data['general_errors']), 0) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) # test the log for email that's send to new created user. info_log.assert_called_with( u"user already exists with username '%s' and email '%s'", 'test_student_1', 'test_student@example.com' ) def test_file_upload_type_not_csv(self): """ Try uploading some non-CSV file and verify that it is rejected """ uploaded_file = SimpleUploadedFile("temp.jpg", io.BytesIO(b"some initial binary data: \x00\x01").read()) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['general_errors']), 0) self.assertEquals(data['general_errors'][0]['response'], 'Make sure that the file you upload is in CSV format with no extraneous characters or rows.') manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) def test_bad_file_upload_type(self): """ Try uploading some non-CSV file and verify that it is rejected """ uploaded_file = SimpleUploadedFile("temp.csv", io.BytesIO(b"some initial binary data: \x00\x01").read()) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['general_errors']), 0) self.assertEquals(data['general_errors'][0]['response'], 'Could not read uploaded file.') manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) def test_insufficient_data(self): """ Try uploading a CSV file which does not have the exact four columns of data """ csv_content = "test_student@example.com,test_student_1\n" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertEquals(len(data['row_errors']), 0) self.assertEquals(len(data['warnings']), 0) self.assertEquals(len(data['general_errors']), 1) self.assertEquals(data['general_errors'][0]['response'], 'Data in row #1 must have exactly four columns: email, username, full name, and country') manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) def test_invalid_email_in_csv(self): """ Test failure case of a poorly formatted email field """ csv_content = "test_student.example.com,test_student_1,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) data = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals(len(data['warnings']), 0) self.assertEquals(len(data['general_errors']), 0) self.assertEquals(data['row_errors'][0]['response'], 'Invalid email {0}.'.format('test_student.example.com')) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) @patch('instructor.views.api.log.info') def test_csv_user_exist_and_not_enrolled(self, info_log): """ If the email address and username already exists and the user is not enrolled in the course, enrolled him/her and iterate to next one. """ csv_content = "nonenrolled@test.com,NotEnrolledStudent,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) info_log.assert_called_with( u'user %s enrolled in the course %s', u'NotEnrolledStudent', self.course.id ) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertTrue(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) def test_user_with_already_existing_email_in_csv(self): """ If the email address already exists, but the username is different, assume it is the correct user and just register the user in the course. """ csv_content = "test_student@example.com,test_student_1,tester1,USA\n" \ "test_student@example.com,test_student_2,tester2,US" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) warning_message = 'An account with email {email} exists but the provided username {username} ' \ 'is different. Enrolling anyway with {email}.'.format(email='test_student@example.com', username='test_student_2') self.assertNotEquals(len(data['warnings']), 0) self.assertEquals(data['warnings'][0]['response'], warning_message) user = User.objects.get(email='test_student@example.com') self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id)) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertTrue(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) def test_user_with_already_existing_username_in_csv(self): """ If the username already exists (but not the email), assume it is a different user and fail to create the new account. """ csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \ "test_student2@example.com,test_student_1,tester2,US" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals(data['row_errors'][0]['response'], 'Username {user} already exists.'.format(user='test_student_1')) def test_csv_file_not_attached(self): """ Test when the user does not attach a file """ csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \ "test_student2@example.com,test_student_1,tester2,US" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'file_not_found': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['general_errors']), 0) self.assertEquals(data['general_errors'][0]['response'], 'File is not attached.') manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) def test_raising_exception_in_auto_registration_and_enrollment_case(self): """ Test that exceptions are handled well """ csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \ "test_student2@example.com,test_student_1,tester2,US" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) with patch('instructor.views.api.create_and_enroll_user') as mock: mock.side_effect = NonExistentCourseError() response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals(data['row_errors'][0]['response'], 'NonExistentCourseError') manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) def test_generate_unique_password(self): """ generate_unique_password should generate a unique password string that excludes certain characters. """ password = generate_unique_password([], 12) self.assertEquals(len(password), 12) for letter in password: self.assertNotIn(letter, 'aAeEiIoOuU1l') def test_users_created_and_enrolled_successfully_if_others_fail(self): csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \ "test_student3@example.com,test_student_1,tester3,CA\n" \ "test_student2@example.com,test_student_2,tester2,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals(data['row_errors'][0]['response'], 'Username {user} already exists.'.format(user='test_student_1')) self.assertTrue(User.objects.filter(username='test_student_1', email='test_student1@example.com').exists()) self.assertTrue(User.objects.filter(username='test_student_2', email='test_student2@example.com').exists()) self.assertFalse(User.objects.filter(email='test_student3@example.com').exists()) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 2) @patch.object(instructor.views.api, 'generate_random_string', Mock(side_effect=['first', 'first', 'second'])) def test_generate_unique_password_no_reuse(self): """ generate_unique_password should generate a unique password string that hasn't been generated before. """ generated_password = ['first'] password = generate_unique_password(generated_password, 12) self.assertNotEquals(password, 'first') @patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': False}) def test_allow_automated_signups_flag_not_set(self): csv_content = "test_student1@example.com,test_student_1,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEquals(response.status_code, 403) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) @attr('shard_1') @ddt.ddt class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test enrollment modification endpoint. This test does NOT exhaustively test state changes, that is the job of test_enrollment. This tests the response and action switch. """ @classmethod def setUpClass(cls): super(TestInstructorAPIEnrollment, cls).setUpClass() cls.course = CourseFactory.create() # Email URL values cls.site_name = microsite.get_value( 'SITE_NAME', settings.SITE_NAME ) cls.about_path = '/courses/{}/about'.format(cls.course.id) cls.course_path = '/courses/{}/'.format(cls.course.id) def setUp(self): super(TestInstructorAPIEnrollment, self).setUp() self.request = RequestFactory().request() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.enrolled_student = UserFactory(username='EnrolledStudent', first_name='Enrolled', last_name='Student') CourseEnrollment.enroll( self.enrolled_student, self.course.id ) self.notenrolled_student = UserFactory(username='NotEnrolledStudent', first_name='NotEnrolled', last_name='Student') # Create invited, but not registered, user cea = CourseEnrollmentAllowed(email='robot-allowed@robot.org', course_id=self.course.id) cea.save() self.allowed_email = 'robot-allowed@robot.org' self.notregistered_email = 'robot-not-an-email-yet@robot.org' self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0) # uncomment to enable enable printing of large diffs # from failed assertions in the event of a test failure. # (comment because pylint C0103(invalid-name)) # self.maxDiff = None def test_missing_params(self): """ Test missing all query parameters. """ url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url) self.assertEqual(response.status_code, 400) def test_bad_action(self): """ Test with an invalid action. """ action = 'robot-not-an-action' url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': action}) self.assertEqual(response.status_code, 400) def test_invalid_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': 'percivaloctavius@', 'action': 'enroll', 'email_students': False}) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "enroll", 'auto_enroll': False, "results": [ { "identifier": 'percivaloctavius@', "invalidIdentifier": True, } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_invalid_username(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': 'percivaloctavius', 'action': 'enroll', 'email_students': False}) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "enroll", 'auto_enroll': False, "results": [ { "identifier": 'percivaloctavius', "invalidIdentifier": True, } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_enroll_with_username(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'enroll', 'email_students': False}) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "enroll", 'auto_enroll': False, "results": [ { "identifier": self.notenrolled_student.username, "before": { "enrollment": False, "auto_enroll": False, "user": True, "allowed": False, }, "after": { "enrollment": True, "auto_enroll": False, "user": True, "allowed": False, } } ] } manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_enroll_without_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': False}) print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email)) self.assertEqual(response.status_code, 200) # test that the user is now enrolled user = User.objects.get(email=self.notenrolled_student.email) self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id)) # test the response data expected = { "action": "enroll", "auto_enroll": False, "results": [ { "identifier": self.notenrolled_student.email, "before": { "enrollment": False, "auto_enroll": False, "user": True, "allowed": False, }, "after": { "enrollment": True, "auto_enroll": False, "user": True, "allowed": False, } } ] } manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 0) @ddt.data('http', 'https') def test_enroll_with_email(self, protocol): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email)) self.assertEqual(response.status_code, 200) # test that the user is now enrolled user = User.objects.get(email=self.notenrolled_student.email) self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id)) # test the response data expected = { "action": "enroll", "auto_enroll": False, "results": [ { "identifier": self.notenrolled_student.email, "before": { "enrollment": False, "auto_enroll": False, "user": True, "allowed": False, }, "after": { "enrollment": True, "auto_enroll": False, "user": True, "allowed": False, } } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, u'You have been enrolled in {}'.format(self.course.display_name) ) self.assertEqual( mail.outbox[0].body, "Dear NotEnrolled Student\n\nYou have been enrolled in {} " "at edx.org by a member of the course staff. " "The course should now appear on your edx.org dashboard.\n\n" "To start accessing course materials, please visit " "{proto}://{site}{course_path}\n\n----\n" "This email was automatically sent from edx.org to NotEnrolled Student".format( self.course.display_name, proto=protocol, site=self.site_name, course_path=self.course_path ) ) @ddt.data('http', 'https') def test_enroll_with_email_not_registered(self, protocol): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) self.assertEqual(response.status_code, 200) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, u'You have been invited to register for {}'.format(self.course.display_name) ) self.assertEqual( mail.outbox[0].body, "Dear student,\n\nYou have been invited to join {} at edx.org by a member of the course staff.\n\n" "To finish your registration, please visit {proto}://{site}/register and fill out the " "registration form making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n" "Once you have registered and activated your account, " "visit {proto}://{site}{about_path} to join the course.\n\n----\n" "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format( self.course.display_name, proto=protocol, site=self.site_name, about_path=self.about_path ) ) @ddt.data('http', 'https') @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_enroll_email_not_registered_mktgsite(self, protocol): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) self.assertEqual(response.status_code, 200) self.assertEqual( mail.outbox[0].body, "Dear student,\n\nYou have been invited to join {display_name}" " at edx.org by a member of the course staff.\n\n" "To finish your registration, please visit {proto}://{site}/register and fill out the registration form " "making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n" "You can then enroll in {display_name}.\n\n----\n" "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format( display_name=self.course.display_name, proto=protocol, site=self.site_name ) ) @ddt.data('http', 'https') def test_enroll_with_email_not_registered_autoenroll(self, protocol): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True, 'auto_enroll': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) print "type(self.notregistered_email): {}".format(type(self.notregistered_email)) self.assertEqual(response.status_code, 200) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, u'You have been invited to register for {}'.format(self.course.display_name) ) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) self.assertEqual( mail.outbox[0].body, "Dear student,\n\nYou have been invited to join {display_name}" " at edx.org by a member of the course staff.\n\n" "To finish your registration, please visit {proto}://{site}/register and fill out the registration form " "making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n" "Once you have registered and activated your account," " you will see {display_name} listed on your dashboard.\n\n----\n" "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format( proto=protocol, site=self.site_name, display_name=self.course.display_name ) ) def test_unenroll_without_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': False}) print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email)) self.assertEqual(response.status_code, 200) # test that the user is now unenrolled user = User.objects.get(email=self.enrolled_student.email) self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id)) # test the response data expected = { "action": "unenroll", "auto_enroll": False, "results": [ { "identifier": self.enrolled_student.email, "before": { "enrollment": True, "auto_enroll": False, "user": True, "allowed": False, }, "after": { "enrollment": False, "auto_enroll": False, "user": True, "allowed": False, } } ] } manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, ENROLLED_TO_UNENROLLED) res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 0) def test_unenroll_with_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': True}) print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email)) self.assertEqual(response.status_code, 200) # test that the user is now unenrolled user = User.objects.get(email=self.enrolled_student.email) self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id)) # test the response data expected = { "action": "unenroll", "auto_enroll": False, "results": [ { "identifier": self.enrolled_student.email, "before": { "enrollment": True, "auto_enroll": False, "user": True, "allowed": False, }, "after": { "enrollment": False, "auto_enroll": False, "user": True, "allowed": False, } } ] } manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, ENROLLED_TO_UNENROLLED) res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, 'You have been un-enrolled from {display_name}'.format(display_name=self.course.display_name,) ) self.assertEqual( mail.outbox[0].body, "Dear Enrolled Student\n\nYou have been un-enrolled in {display_name} " "at edx.org by a member of the course staff. " "The course will no longer appear on your edx.org dashboard.\n\n" "Your other courses have not been affected.\n\n----\n" "This email was automatically sent from edx.org to Enrolled Student".format( display_name=self.course.display_name, ) ) def test_unenroll_with_email_allowed_student(self): url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.allowed_email, 'action': 'unenroll', 'email_students': True}) print "type(self.allowed_email): {}".format(type(self.allowed_email)) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "unenroll", "auto_enroll": False, "results": [ { "identifier": self.allowed_email, "before": { "enrollment": False, "auto_enroll": False, "user": False, "allowed": True, }, "after": { "enrollment": False, "auto_enroll": False, "user": False, "allowed": False, } } ] } manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, ALLOWEDTOENROLL_TO_UNENROLLED) res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, 'You have been un-enrolled from {display_name}'.format(display_name=self.course.display_name,) ) self.assertEqual( mail.outbox[0].body, "Dear Student,\n\nYou have been un-enrolled from course {display_name} by a member of the course staff. " "Please disregard the invitation previously sent.\n\n----\n" "This email was automatically sent from edx.org to robot-allowed@robot.org".format( display_name=self.course.display_name, ) ) @ddt.data('http', 'https') @patch('instructor.enrollment.uses_shib') def test_enroll_with_email_not_registered_with_shib(self, protocol, mock_uses_shib): mock_uses_shib.return_value = True url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) self.assertEqual(response.status_code, 200) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, 'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) ) self.assertEqual( mail.outbox[0].body, "Dear student,\n\nYou have been invited to join {display_name} at edx.org by a member of the course staff.\n\n" "To access the course visit {proto}://{site}{about_path} and register for the course.\n\n----\n" "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format( proto=protocol, site=self.site_name, about_path=self.about_path, display_name=self.course.display_name, ) ) @patch('instructor.enrollment.uses_shib') @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_enroll_email_not_registered_shib_mktgsite(self, mock_uses_shib): # Try with marketing site enabled and shib on mock_uses_shib.return_value = True url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) # Try with marketing site enabled with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}): response = self.client.post(url, {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}) self.assertEqual(response.status_code, 200) self.assertEqual( mail.outbox[0].body, "Dear student,\n\nYou have been invited to join {} at edx.org by a member of the course staff.\n\n----\n" "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format( self.course.display_name, ) ) @ddt.data('http', 'https') @patch('instructor.enrollment.uses_shib') def test_enroll_with_email_not_registered_with_shib_autoenroll(self, protocol, mock_uses_shib): mock_uses_shib.return_value = True url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True, 'auto_enroll': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) print "type(self.notregistered_email): {}".format(type(self.notregistered_email)) self.assertEqual(response.status_code, 200) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, 'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) ) self.assertEqual( mail.outbox[0].body, "Dear student,\n\nYou have been invited to join {display_name}" " at edx.org by a member of the course staff.\n\n" "To access the course visit {proto}://{site}{course_path} and login.\n\n----\n" "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format( display_name=self.course.display_name, proto=protocol, site=self.site_name, course_path=self.course_path ) ) def test_enroll_already_enrolled_student(self): """ Ensure that already enrolled "verified" students cannot be downgraded to "honor" """ course_enrollment = CourseEnrollment.objects.get( user=self.enrolled_student, course_id=self.course.id ) # make this enrollment "verified" course_enrollment.mode = u'verified' course_enrollment.save() self.assertEqual(course_enrollment.mode, u'verified') # now re-enroll the student through the instructor dash self._change_student_enrollment(self.enrolled_student, self.course, 'enroll') # affirm that the student is still in "verified" mode course_enrollment = CourseEnrollment.objects.get( user=self.enrolled_student, course_id=self.course.id ) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, ENROLLED_TO_ENROLLED) self.assertEqual(course_enrollment.mode, u"verified") def create_paid_course(self): """ create paid course mode. """ paid_course = CourseFactory.create() CourseModeFactory.create(course_id=paid_course.id, min_price=50) CourseInstructorRole(paid_course.id).add_users(self.instructor) return paid_course def test_reason_field_should_not_be_empty(self): """ test to check that reason field should not be empty when manually enrolling the students for the paid courses. """ paid_course = self.create_paid_course() url = reverse('students_update_enrollment', kwargs={'course_id': paid_course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': False, 'auto_enroll': False} response = self.client.post(url, params) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) # test the response data expected = { "action": "enroll", "auto_enroll": False, "results": [ { "error": True } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_unenrolled_allowed_to_enroll_user(self): """ test to unenroll allow to enroll user. """ paid_course = self.create_paid_course() url = reverse('students_update_enrollment', kwargs={'course_id': paid_course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': False, 'auto_enroll': False, 'reason': 'testing..'} response = self.client.post(url, params) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) self.assertEqual(response.status_code, 200) # now registered the user UserFactory(email=self.notregistered_email) url = reverse('students_update_enrollment', kwargs={'course_id': paid_course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': False, 'auto_enroll': False, 'reason': 'testing'} response = self.client.post(url, params) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 2) self.assertEqual(manual_enrollments[1].state_transition, ALLOWEDTOENROLL_TO_ENROLLED) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "enroll", "auto_enroll": False, "results": [ { "identifier": self.notregistered_email, "before": { "enrollment": False, "auto_enroll": False, "user": True, "allowed": True, }, "after": { "enrollment": True, "auto_enroll": False, "user": True, "allowed": True, } } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_unenrolled_already_not_enrolled_user(self): """ test unenrolled user already not enrolled in a course. """ paid_course = self.create_paid_course() course_enrollment = CourseEnrollment.objects.filter( user__email=self.notregistered_email, course_id=paid_course.id ) self.assertEqual(course_enrollment.count(), 0) url = reverse('students_update_enrollment', kwargs={'course_id': paid_course.id.to_deprecated_string()}) params = {'identifiers': self.notregistered_email, 'action': 'unenroll', 'email_students': False, 'auto_enroll': False, 'reason': 'testing'} response = self.client.post(url, params) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "unenroll", "auto_enroll": False, "results": [ { "identifier": self.notregistered_email, "before": { "enrollment": False, "auto_enroll": False, "user": False, "allowed": False, }, "after": { "enrollment": False, "auto_enroll": False, "user": False, "allowed": False, } } ] } manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 1) self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_UNENROLLED) res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_unenroll_and_enroll_verified(self): """ Test that unenrolling and enrolling a student from a verified track results in that student being in an honor track """ course_enrollment = CourseEnrollment.objects.get( user=self.enrolled_student, course_id=self.course.id ) # upgrade enrollment course_enrollment.mode = u'verified' course_enrollment.save() self.assertEqual(course_enrollment.mode, u'verified') self._change_student_enrollment(self.enrolled_student, self.course, 'unenroll') self._change_student_enrollment(self.enrolled_student, self.course, 'enroll') course_enrollment = CourseEnrollment.objects.get( user=self.enrolled_student, course_id=self.course.id ) self.assertEqual(course_enrollment.mode, u'honor') def _change_student_enrollment(self, user, course, action): """ Helper function that posts to 'students_update_enrollment' to change a student's enrollment """ url = reverse( 'students_update_enrollment', kwargs={'course_id': course.id.to_deprecated_string()}, ) params = { 'identifiers': user.email, 'action': action, 'email_students': True, 'reason': 'change user enrollment' } response = self.client.post(url, params) self.assertEqual(response.status_code, 200) return response @attr('shard_1') @ddt.ddt class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test bulk beta modify access endpoint. """ @classmethod def setUpClass(cls): super(TestInstructorAPIBulkBetaEnrollment, cls).setUpClass() cls.course = CourseFactory.create() # Email URL values cls.site_name = microsite.get_value( 'SITE_NAME', settings.SITE_NAME ) cls.about_path = '/courses/{}/about'.format(cls.course.id) cls.course_path = '/courses/{}/'.format(cls.course.id) def setUp(self): super(TestInstructorAPIBulkBetaEnrollment, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.beta_tester = BetaTesterFactory(course_key=self.course.id) CourseEnrollment.enroll( self.beta_tester, self.course.id ) self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester)) self.notenrolled_student = UserFactory(username='NotEnrolledStudent') self.notregistered_email = 'robot-not-an-email-yet@robot.org' self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0) self.request = RequestFactory().request() # uncomment to enable enable printing of large diffs # from failed assertions in the event of a test failure. # (comment because pylint C0103(invalid-name)) # self.maxDiff = None def test_missing_params(self): """ Test missing all query parameters. """ url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url) self.assertEqual(response.status_code, 400) def test_bad_action(self): """ Test with an invalid action. """ action = 'robot-not-an-action' url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': action}) self.assertEqual(response.status_code, 400) def add_notenrolled(self, response, identifier): """ Test Helper Method (not a test, called by other tests) Takes a client response from a call to bulk_beta_modify_access with 'email_students': False, and the student identifier (email or username) given as 'identifiers' in the request. Asserts the reponse returns cleanly, that the student was added as a beta tester, and the response properly contains their identifier, 'error': False, and 'userDoesNotExist': False. Additionally asserts no email was sent. """ self.assertEqual(response.status_code, 200) self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student)) # test the response data expected = { "action": "add", "results": [ { "identifier": identifier, "error": False, "userDoesNotExist": False } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 0) def test_add_notenrolled_email(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False}) self.add_notenrolled(response, self.notenrolled_student.email) self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) def test_add_notenrolled_email_autoenroll(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False, 'auto_enroll': True}) self.add_notenrolled(response, self.notenrolled_student.email) self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) def test_add_notenrolled_username(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False}) self.add_notenrolled(response, self.notenrolled_student.username) self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) def test_add_notenrolled_username_autoenroll(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False, 'auto_enroll': True}) self.add_notenrolled(response, self.notenrolled_student.username) self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) @ddt.data('http', 'https') def test_add_notenrolled_with_email(self, protocol): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) self.assertEqual(response.status_code, 200) self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student)) # test the response data expected = { "action": "add", "results": [ { "identifier": self.notenrolled_student.email, "error": False, "userDoesNotExist": False } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, 'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name,) ) self.assertEqual( mail.outbox[0].body, u"Dear {student_name}\n\nYou have been invited to be a beta tester " "for {display_name} at edx.org by a member of the course staff.\n\n" "Visit {proto}://{site}{about_path} to join " "the course and begin the beta test.\n\n----\n" "This email was automatically sent from edx.org to {student_email}".format( display_name=self.course.display_name, student_name=self.notenrolled_student.profile.name, student_email=self.notenrolled_student.email, proto=protocol, site=self.site_name, about_path=self.about_path ) ) @ddt.data('http', 'https') def test_add_notenrolled_with_email_autoenroll(self, protocol): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True, 'auto_enroll': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) self.assertEqual(response.status_code, 200) self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student)) # test the response data expected = { "action": "add", "results": [ { "identifier": self.notenrolled_student.email, "error": False, "userDoesNotExist": False } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, 'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name) ) self.assertEqual( mail.outbox[0].body, u"Dear {student_name}\n\nYou have been invited to be a beta tester " "for {display_name} at edx.org by a member of the course staff.\n\n" "To start accessing course materials, please visit " "{proto}://{site}{course_path}\n\n----\n" "This email was automatically sent from edx.org to {student_email}".format( display_name=self.course.display_name, student_name=self.notenrolled_student.profile.name, student_email=self.notenrolled_student.email, proto=protocol, site=self.site_name, course_path=self.course_path ) ) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_add_notenrolled_email_mktgsite(self): # Try with marketing site enabled url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True}) self.assertEqual(response.status_code, 200) self.assertEqual( mail.outbox[0].body, u"Dear {}\n\nYou have been invited to be a beta tester " "for {} at edx.org by a member of the course staff.\n\n" "Visit edx.org to enroll in the course and begin the beta test.\n\n----\n" "This email was automatically sent from edx.org to {}".format( self.notenrolled_student.profile.name, self.course.display_name, self.notenrolled_student.email, ) ) def test_enroll_with_email_not_registered(self): # User doesn't exist url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.notregistered_email, 'action': 'add', 'email_students': True, 'reason': 'testing'}) self.assertEqual(response.status_code, 200) # test the response data expected = { "action": "add", "results": [ { "identifier": self.notregistered_email, "error": True, "userDoesNotExist": True } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 0) def test_remove_without_email(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': False, 'reason': 'testing'}) self.assertEqual(response.status_code, 200) # Works around a caching bug which supposedly can't happen in prod. The instance here is not == # the instance fetched from the email above which had its cache cleared if hasattr(self.beta_tester, '_roles'): del self.beta_tester._roles self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester)) # test the response data expected = { "action": "remove", "results": [ { "identifier": self.beta_tester.email, "error": False, "userDoesNotExist": False } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 0) def test_remove_with_email(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': True, 'reason': 'testing'}) self.assertEqual(response.status_code, 200) # Works around a caching bug which supposedly can't happen in prod. The instance here is not == # the instance fetched from the email above which had its cache cleared if hasattr(self.beta_tester, '_roles'): del self.beta_tester._roles self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester)) # test the response data expected = { "action": "remove", "results": [ { "identifier": self.beta_tester.email, "error": False, "userDoesNotExist": False } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, u'You have been removed from a beta test for {display_name}'.format(display_name=self.course.display_name,) ) self.assertEqual( mail.outbox[0].body, "Dear {full_name}\n\nYou have been removed as a beta tester for " "{display_name} at edx.org by a member of the course staff. " "The course will remain on your dashboard, but you will no longer " "be part of the beta testing group.\n\n" "Your other courses have not been affected.\n\n----\n" "This email was automatically sent from edx.org to {email_address}".format( display_name=self.course.display_name, full_name=self.beta_tester.profile.name, email_address=self.beta_tester.email ) ) @attr('shard_1') class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test endpoints whereby instructors can change permissions of other users. This test does NOT test whether the actions had an effect on the database, that is the job of test_access. This tests the response and action switch. Actually, modify_access does not have a very meaningful response yet, so only the status code is tested. """ @classmethod def setUpClass(cls): super(TestInstructorAPILevelsAccess, cls).setUpClass() cls.course = CourseFactory.create() def setUp(self): super(TestInstructorAPILevelsAccess, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.other_instructor = InstructorFactory(course_key=self.course.id) self.other_staff = StaffFactory(course_key=self.course.id) self.other_user = UserFactory() def test_modify_access_noparams(self): """ Test missing all query parameters. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400) def test_modify_access_bad_action(self): """ Test with an invalid action parameter. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'staff', 'action': 'robot-not-an-action', }) self.assertEqual(response.status_code, 400) def test_modify_access_bad_role(self): """ Test with an invalid action parameter. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'robot-not-a-roll', 'action': 'revoke', }) self.assertEqual(response.status_code, 400) def test_modify_access_allow(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_user.email, 'rolename': 'staff', 'action': 'allow', }) self.assertEqual(response.status_code, 200) def test_modify_access_allow_with_uname(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_instructor.username, 'rolename': 'staff', 'action': 'allow', }) self.assertEqual(response.status_code, 200) def test_modify_access_revoke(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'staff', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) def test_modify_access_revoke_with_username(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.username, 'rolename': 'staff', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) def test_modify_access_with_fake_user(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': 'GandalfTheGrey', 'rolename': 'staff', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) expected = { 'unique_student_identifier': 'GandalfTheGrey', 'userDoesNotExist': True, } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_modify_access_with_inactive_user(self): self.other_user.is_active = False self.other_user.save() # pylint: disable=no-member url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_user.username, 'rolename': 'beta', 'action': 'allow', }) self.assertEqual(response.status_code, 200) expected = { 'unique_student_identifier': self.other_user.username, 'inactiveUser': True, } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_modify_access_revoke_not_allowed(self): """ Test revoking access that a user does not have. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'instructor', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) def test_modify_access_revoke_self(self): """ Test that an instructor cannot remove instructor privelages from themself. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.instructor.email, 'rolename': 'instructor', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) # check response content expected = { 'unique_student_identifier': self.instructor.username, 'rolename': 'instructor', 'action': 'revoke', 'removingSelfAsInstructor': True, } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_list_course_role_members_noparams(self): """ Test missing all query parameters. """ url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400) def test_list_course_role_members_bad_rolename(self): """ Test with an invalid rolename parameter. """ url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'rolename': 'robot-not-a-rolename', }) self.assertEqual(response.status_code, 400) def test_list_course_role_members_staff(self): url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'rolename': 'staff', }) self.assertEqual(response.status_code, 200) # check response content expected = { 'course_id': self.course.id.to_deprecated_string(), 'staff': [ { 'username': self.other_staff.username, 'email': self.other_staff.email, 'first_name': self.other_staff.first_name, 'last_name': self.other_staff.last_name, } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_list_course_role_members_beta(self): url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'rolename': 'beta', }) self.assertEqual(response.status_code, 200) # check response content expected = { 'course_id': self.course.id.to_deprecated_string(), 'beta': [] } res_json = json.loads(response.content) self.assertEqual(res_json, expected) def test_update_forum_role_membership(self): """ Test update forum role membership with user's email and username. """ # Seed forum roles for course. seed_permissions_roles(self.course.id) for user in [self.instructor, self.other_user]: for identifier_attr in [user.email, user.username]: for rolename in ["Administrator", "Moderator", "Community TA"]: for action in ["allow", "revoke"]: self.assert_update_forum_role_membership(user, identifier_attr, rolename, action) def assert_update_forum_role_membership(self, current_user, identifier, rolename, action): """ Test update forum role membership. Get unique_student_identifier, rolename and action and update forum role. """ url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get( url, { 'unique_student_identifier': identifier, 'rolename': rolename, 'action': action, } ) # Status code should be 200. self.assertEqual(response.status_code, 200) user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True) if action == 'allow': self.assertIn(rolename, user_roles) elif action == 'revoke': self.assertNotIn(rolename, user_roles) @attr('shard_1') @ddt.ddt @patch.dict('django.conf.settings.FEATURES', {'ENABLE_PAID_COURSE_REGISTRATION': True}) class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test endpoints that show data without side effects. """ @classmethod def setUpClass(cls): super(TestInstructorAPILevelsDataDump, cls).setUpClass() cls.course = CourseFactory.create() def setUp(self): super(TestInstructorAPILevelsDataDump, self).setUp() self.course_mode = CourseMode(course_id=self.course.id, mode_slug="honor", mode_display_name="honor cert", min_price=40) self.course_mode.save() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.cart = Order.get_cart_for_user(self.instructor) self.coupon_code = 'abcde' self.coupon = Coupon(code=self.coupon_code, description='testing code', course_id=self.course.id, percentage_discount=10, created_by=self.instructor, is_active=True) self.coupon.save() # Create testing invoice 1 self.sale_invoice_1 = Invoice.objects.create( total_amount=1234.32, company_name='Test1', company_contact_name='TestName', company_contact_email='Test@company.com', recipient_name='Testw', recipient_email='test1@test.com', customer_reference_number='2Fwe23S', internal_reference="A", course_id=self.course.id, is_valid=True ) self.invoice_item = CourseRegistrationCodeInvoiceItem.objects.create( invoice=self.sale_invoice_1, qty=1, unit_price=1234.32, course_id=self.course.id ) self.students = [UserFactory() for _ in xrange(6)] for student in self.students: CourseEnrollment.enroll(student, self.course.id) self.students_who_may_enroll = self.students + [UserFactory() for _ in range(5)] for student in self.students_who_may_enroll: CourseEnrollmentAllowed.objects.create( email=student.email, course_id=self.course.id ) def register_with_redemption_code(self, user, code): """ enroll user using a registration code """ redeem_url = reverse('register_code_redemption', args=[code]) self.client.login(username=user.username, password='test') response = self.client.get(redeem_url) self.assertEquals(response.status_code, 200) # check button text self.assertTrue('Activate Course Enrollment' in response.content) response = self.client.post(redeem_url) self.assertEquals(response.status_code, 200) def test_invalidate_sale_record(self): """ Testing the sale invalidating scenario. """ for i in range(2): course_registration_code = CourseRegistrationCode( code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) course_registration_code.save() data = {'invoice_number': self.sale_invoice_1.id, 'event_type': "invalidate"} url = reverse('sale_validation', kwargs={'course_id': self.course.id.to_deprecated_string()}) self.assert_request_status_code(200, url, method="POST", data=data) #Now try to fetch data against not existing invoice number test_data_1 = {'invoice_number': 100, 'event_type': "invalidate"} self.assert_request_status_code(404, url, method="POST", data=test_data_1) # Now invalidate the same invoice number and expect an Bad request response = self.assert_request_status_code(400, url, method="POST", data=data) self.assertIn("The sale associated with this invoice has already been invalidated.", response.content) # now re_validate the invoice number data['event_type'] = "re_validate" self.assert_request_status_code(200, url, method="POST", data=data) # Now re_validate the same active invoice number and expect an Bad request response = self.assert_request_status_code(400, url, method="POST", data=data) self.assertIn("This invoice is already active.", response.content) test_data_2 = {'invoice_number': self.sale_invoice_1.id} response = self.assert_request_status_code(400, url, method="POST", data=test_data_2) self.assertIn("Missing required event_type parameter", response.content) test_data_3 = {'event_type': "re_validate"} response = self.assert_request_status_code(400, url, method="POST", data=test_data_3) self.assertIn("Missing required invoice_number parameter", response.content) # submitting invalid invoice number data['invoice_number'] = 'testing' response = self.assert_request_status_code(400, url, method="POST", data=data) self.assertIn("invoice_number must be an integer, {value} provided".format(value=data['invoice_number']), response.content) def test_get_sale_order_records_features_csv(self): """ Test that the response from get_sale_order_records is in csv format. """ # add the coupon code for the course coupon = Coupon( code='test_code', description='test_description', course_id=self.course.id, percentage_discount='10', created_by=self.instructor, is_active=True ) coupon.save() self.cart.order_type = 'business' self.cart.save() self.cart.add_billing_details(company_name='Test Company', company_contact_name='Test', company_contact_email='test@123', recipient_name='R1', recipient_email='', customer_reference_number='PO#23') paid_course_reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course.id) # update the quantity of the cart item paid_course_reg_item resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), {'ItemId': paid_course_reg_item.id, 'qty': '4'}) self.assertEqual(resp.status_code, 200) # apply the coupon code to the item in the cart resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code}) self.assertEqual(resp.status_code, 200) self.cart.purchase() # get the updated item item = self.cart.orderitem_set.all().select_subclasses()[0] # get the redeemed coupon information coupon_redemption = CouponRedemption.objects.select_related('coupon').filter(order=self.cart) sale_order_url = reverse('get_sale_order_records', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(sale_order_url) self.assertEqual(response['Content-Type'], 'text/csv') self.assertIn('36', response.content.split('\r\n')[1]) self.assertIn(str(item.unit_cost), response.content.split('\r\n')[1],) self.assertIn(str(item.list_price), response.content.split('\r\n')[1],) self.assertIn(item.status, response.content.split('\r\n')[1],) self.assertIn(coupon_redemption[0].coupon.code, response.content.split('\r\n')[1],) def test_coupon_redeem_count_in_ecommerce_section(self): """ Test that checks the redeem count in the instructor_dashboard coupon section """ # add the coupon code for the course coupon = Coupon( code='test_code', description='test_description', course_id=self.course.id, percentage_discount='10', created_by=self.instructor, is_active=True ) coupon.save() # Coupon Redeem Count only visible for Financial Admins. CourseFinanceAdminRole(self.course.id).add_users(self.instructor) PaidCourseRegistration.add_to_order(self.cart, self.course.id) # apply the coupon code to the item in the cart resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code}) self.assertEqual(resp.status_code, 200) # URL for instructor dashboard instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) # visit the instructor dashboard page and # check that the coupon redeem count should be 0 resp = self.client.get(instructor_dashboard) self.assertEqual(resp.status_code, 200) self.assertIn('Number Redeemed', resp.content) self.assertIn('<td>0</td>', resp.content) # now make the payment of your cart items self.cart.purchase() # visit the instructor dashboard page and # check that the coupon redeem count should be 1 resp = self.client.get(instructor_dashboard) self.assertEqual(resp.status_code, 200) self.assertIn('Number Redeemed', resp.content) self.assertIn('<td>1</td>', resp.content) def test_get_sale_records_features_csv(self): """ Test that the response from get_sale_records is in csv format. """ for i in range(2): course_registration_code = CourseRegistrationCode( code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) course_registration_code.save() url = reverse( 'get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()} ) response = self.client.get(url + '/csv', {}) self.assertEqual(response['Content-Type'], 'text/csv') def test_get_sale_records_features_json(self): """ Test that the response from get_sale_records is in json format. """ for i in range(5): course_registration_code = CourseRegistrationCode( code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) course_registration_code.save() url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('sale', res_json) for res in res_json['sale']: self.validate_sale_records_response( res, course_registration_code, self.sale_invoice_1, 0, invoice_item=self.invoice_item ) def test_get_sale_records_features_with_multiple_invoices(self): """ Test that the response from get_sale_records is in json format for multiple invoices """ for i in range(5): course_registration_code = CourseRegistrationCode( code='qwerty{}'.format(i), course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) course_registration_code.save() # Create test invoice 2 sale_invoice_2 = Invoice.objects.create( total_amount=1234.32, company_name='Test1', company_contact_name='TestName', company_contact_email='Test@company.com', recipient_name='Testw_2', recipient_email='test2@test.com', customer_reference_number='2Fwe23S', internal_reference="B", course_id=self.course.id ) invoice_item_2 = CourseRegistrationCodeInvoiceItem.objects.create( invoice=sale_invoice_2, qty=1, unit_price=1234.32, course_id=self.course.id ) for i in range(5): course_registration_code = CourseRegistrationCode( code='xyzmn{}'.format(i), course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=sale_invoice_2, invoice_item=invoice_item_2, mode_slug='honor' ) course_registration_code.save() url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('sale', res_json) self.validate_sale_records_response( res_json['sale'][0], course_registration_code, self.sale_invoice_1, 0, invoice_item=self.invoice_item ) self.validate_sale_records_response( res_json['sale'][1], course_registration_code, sale_invoice_2, 0, invoice_item=invoice_item_2 ) def validate_sale_records_response(self, res, course_registration_code, invoice, used_codes, invoice_item): """ validate sale records attribute values with the response object """ self.assertEqual(res['total_amount'], invoice.total_amount) self.assertEqual(res['recipient_email'], invoice.recipient_email) self.assertEqual(res['recipient_name'], invoice.recipient_name) self.assertEqual(res['company_name'], invoice.company_name) self.assertEqual(res['company_contact_name'], invoice.company_contact_name) self.assertEqual(res['company_contact_email'], invoice.company_contact_email) self.assertEqual(res['internal_reference'], invoice.internal_reference) self.assertEqual(res['customer_reference_number'], invoice.customer_reference_number) self.assertEqual(res['invoice_number'], invoice.id) self.assertEqual(res['created_by'], course_registration_code.created_by.username) self.assertEqual(res['course_id'], invoice_item.course_id.to_deprecated_string()) self.assertEqual(res['total_used_codes'], used_codes) self.assertEqual(res['total_codes'], 5) def test_get_problem_responses_invalid_location(self): """ Test whether get_problem_responses returns an appropriate status message when users submit an invalid problem location. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.course.id)} ) problem_location = '' response = self.client.get(url, {'problem_location': problem_location}) res_json = json.loads(response.content) self.assertEqual(res_json, 'Could not find problem with this location.') def valid_problem_location(test): # pylint: disable=no-self-argument """ Decorator for tests that target get_problem_responses endpoint and need to pretend user submitted a valid problem location. """ @functools.wraps(test) def wrapper(self, *args, **kwargs): """ Run `test` method, ensuring that UsageKey.from_string returns a problem key that the get_problem_responses endpoint can work with. """ mock_problem_key = Mock(return_value=u'') mock_problem_key.course_key = self.course.id with patch.object(UsageKey, 'from_string') as patched_method: patched_method.return_value = mock_problem_key test(self, *args, **kwargs) return wrapper @valid_problem_location def test_get_problem_responses_successful(self): """ Test whether get_problem_responses returns an appropriate status message if CSV generation was started successfully. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.course.id)} ) problem_location = '' response = self.client.get(url, {'problem_location': problem_location}) res_json = json.loads(response.content) self.assertIn('status', res_json) status = res_json['status'] self.assertIn('is being created', status) self.assertNotIn('already in progress', status) @valid_problem_location def test_get_problem_responses_already_running(self): """ Test whether get_problem_responses returns an appropriate status message if CSV generation is already in progress. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.course.id)} ) with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function: error = AlreadyRunningError() submit_task_function.side_effect = error response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertIn('already in progress', res_json['status']) def test_get_students_features(self): """ Test that some minimum of information is formatted correctly in the response to get_students_features. """ url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('students', res_json) for student in self.students: student_json = [ x for x in res_json['students'] if x['username'] == student.username ][0] self.assertEqual(student_json['username'], student.username) self.assertEqual(student_json['email'], student.email) @ddt.data(True, False) def test_get_students_features_cohorted(self, is_cohorted): """ Test that get_students_features includes cohort info when the course is cohorted, and does not when the course is not cohorted. """ url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)}) set_course_cohort_settings(self.course.id, is_cohorted=is_cohorted) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertEqual('cohort' in res_json['feature_names'], is_cohorted) @ddt.data(True, False) def test_get_students_features_teams(self, has_teams): """ Test that get_students_features includes team info when the course is has teams enabled, and does not when the course does not have teams enabled """ if has_teams: self.course = CourseFactory.create(teams_configuration={ 'max_size': 2, 'topics': [{'topic-id': 'topic', 'name': 'Topic', 'description': 'A Topic'}] }) course_instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=course_instructor.username, password='test') url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertEqual('team' in res_json['feature_names'], has_teams) def test_get_students_who_may_enroll(self): """ Test whether get_students_who_may_enroll returns an appropriate status message when users request a CSV file of students who may enroll in a course. """ url = reverse( 'get_students_who_may_enroll', kwargs={'course_id': unicode(self.course.id)} ) # Successful case: response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertNotIn('currently being created', res_json['status']) # CSV generation already in progress: with patch('instructor_task.api.submit_calculate_may_enroll_csv') as submit_task_function: error = AlreadyRunningError() submit_task_function.side_effect = error response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertIn('currently being created', res_json['status']) def test_get_student_exam_results(self): """ Test whether get_proctored_exam_results returns an appropriate status message when users request a CSV file. """ url = reverse( 'get_proctored_exam_results', kwargs={'course_id': unicode(self.course.id)} ) # Successful case: response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertNotIn('currently being created', res_json['status']) # CSV generation already in progress: with patch('instructor_task.api.submit_proctored_exam_results_report') as submit_task_function: error = AlreadyRunningError() submit_task_function.side_effect = error response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertIn('currently being created', res_json['status']) def test_access_course_finance_admin_with_invalid_course_key(self): """ Test assert require_course fiance_admin before generating a detailed enrollment report """ func = Mock() decorated_func = require_finance_admin(func) request = self.mock_request() response = decorated_func(request, 'invalid_course_key') self.assertEqual(response.status_code, 404) self.assertFalse(func.called) def mock_request(self): """ mock request """ request = Mock() request.user = self.instructor return request def test_access_course_finance_admin_with_valid_course_key(self): """ Test to check the course_finance_admin role with valid key but doesn't have access to the function """ func = Mock() decorated_func = require_finance_admin(func) request = self.mock_request() response = decorated_func(request, 'valid/course/key') self.assertEqual(response.status_code, 403) self.assertFalse(func.called) def test_add_user_to_fiance_admin_role_with_valid_course(self): """ test to check that a function is called using a fiance_admin rights. """ func = Mock() decorated_func = require_finance_admin(func) request = self.mock_request() CourseFinanceAdminRole(self.course.id).add_users(self.instructor) decorated_func(request, self.course.id.to_deprecated_string()) self.assertTrue(func.called) def test_enrollment_report_features_csv(self): """ test to generate enrollment report. enroll users, admin staff using registration codes. """ InvoiceTransaction.objects.create( invoice=self.sale_invoice_1, amount=self.sale_invoice_1.total_amount, status='completed', created_by=self.instructor, last_modified_by=self.instructor ) course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) admin_user = AdminFactory() admin_cart = Order.get_cart_for_user(admin_user) PaidCourseRegistration.add_to_order(admin_cart, self.course.id) admin_cart.purchase() # create a new user/student and enroll # in the course using a registration code # and then validates the generated detailed enrollment report test_user = UserFactory() self.register_with_redemption_code(test_user, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) UserProfileFactory.create(user=self.students[0], meta='{"company": "asdasda"}') self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content) def test_bulk_purchase_detailed_report(self): """ test to generate detailed enrollment report. 1 Purchase registration codes. 2 Enroll users via registration code. 3 Validate generated enrollment report. """ paid_course_reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course.id) # update the quantity of the cart item paid_course_reg_item resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), {'ItemId': paid_course_reg_item.id, 'qty': '4'}) self.assertEqual(resp.status_code, 200) # apply the coupon code to the item in the cart resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.coupon_code}) self.assertEqual(resp.status_code, 200) self.cart.purchase() course_reg_codes = CourseRegistrationCode.objects.filter(order=self.cart) self.register_with_redemption_code(self.instructor, course_reg_codes[0].code) test_user = UserFactory() test_user_cart = Order.get_cart_for_user(test_user) PaidCourseRegistration.add_to_order(test_user_cart, self.course.id) test_user_cart.purchase() InvoiceTransaction.objects.create( invoice=self.sale_invoice_1, amount=-self.sale_invoice_1.total_amount, status='refunded', created_by=self.instructor, last_modified_by=self.instructor ) course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) test_user1 = UserFactory() self.register_with_redemption_code(test_user1, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content) def test_create_registration_code_without_invoice_and_order(self): """ test generate detailed enrollment report, used a registration codes which has been created via invoice or bulk purchase scenario. """ course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, mode_slug='honor' ) test_user1 = UserFactory() self.register_with_redemption_code(test_user1, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content) def test_invoice_payment_is_still_pending_for_registration_codes(self): """ test generate enrollment report enroll a user in a course using registration code whose invoice has not been paid yet """ course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) test_user1 = UserFactory() self.register_with_redemption_code(test_user1, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content) @patch.object(instructor.views.api, 'anonymous_id_for_user', Mock(return_value='42')) @patch.object(instructor.views.api, 'unique_id_for_user', Mock(return_value='41')) def test_get_anon_ids(self): """ Test the CSV output for the anonymized user ids. """ url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith( '"User ID","Anonymized User ID","Course Specific Anonymized User ID"' '\n"{user_id}","41","42"\n'.format(user_id=self.students[0].id) )) self.assertTrue( body.endswith('"{user_id}","41","42"\n'.format(user_id=self.students[-1].id)) ) def test_list_report_downloads(self): url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()}) with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for: mock_links_for.return_value = [ ('mock_file_name_1', 'https://1.mock.url'), ('mock_file_name_2', 'https://2.mock.url'), ] response = self.client.get(url, {}) expected_response = { "downloads": [ { "url": "https://1.mock.url", "link": "<a href=\"https://1.mock.url\">mock_file_name_1</a>", "name": "mock_file_name_1" }, { "url": "https://2.mock.url", "link": "<a href=\"https://2.mock.url\">mock_file_name_2</a>", "name": "mock_file_name_2" } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected_response) @ddt.data(*REPORTS_DATA) @ddt.unpack @valid_problem_location def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs): kwargs = {'course_id': unicode(self.course.id)} kwargs.update(extra_instructor_api_kwargs) url = reverse(instructor_api_endpoint, kwargs=kwargs) success_status = "The {report_type} report is being created.".format(report_type=report_type) if report_type == 'problem responses': with patch(task_api_endpoint): response = self.client.get(url, {'problem_location': ''}) self.assertIn(success_status, response.content) else: CourseFinanceAdminRole(self.course.id).add_users(self.instructor) with patch(task_api_endpoint): response = self.client.get(url, {}) self.assertIn(success_status, response.content) @ddt.data(*EXECUTIVE_SUMMARY_DATA) @ddt.unpack def test_executive_summary_report_success( self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs ): kwargs = {'course_id': unicode(self.course.id)} kwargs.update(extra_instructor_api_kwargs) url = reverse(instructor_api_endpoint, kwargs=kwargs) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) with patch(task_api_endpoint): response = self.client.get(url, {}) success_status = "The {report_type} report is being created." \ " To view the status of the report, see Pending" \ " Instructor Tasks" \ " below".format(report_type=report_type) self.assertIn(success_status, response.content) @ddt.data(*EXECUTIVE_SUMMARY_DATA) @ddt.unpack def test_executive_summary_report_already_running( self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs ): kwargs = {'course_id': unicode(self.course.id)} kwargs.update(extra_instructor_api_kwargs) url = reverse(instructor_api_endpoint, kwargs=kwargs) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) with patch(task_api_endpoint) as mock: mock.side_effect = AlreadyRunningError() response = self.client.get(url, {}) already_running_status = "The {report_type} report is currently being created." \ " To view the status of the report, see Pending Instructor Tasks below." \ " You will be able to download the report" \ " when it is" \ " complete.".format(report_type=report_type) self.assertIn(already_running_status, response.content) def test_get_student_progress_url(self): """ Test that progress_url is in the successful response. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) url += "?unique_student_identifier={}".format( quote(self.students[0].email.encode("utf-8")) ) response = self.client.get(url) self.assertEqual(response.status_code, 200) res_json = json.loads(response.content) self.assertIn('progress_url', res_json) def test_get_student_progress_url_from_uname(self): """ Test that progress_url is in the successful response. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) url += "?unique_student_identifier={}".format( quote(self.students[0].username.encode("utf-8")) ) response = self.client.get(url) self.assertEqual(response.status_code, 200) res_json = json.loads(response.content) self.assertIn('progress_url', res_json) def test_get_student_progress_url_noparams(self): """ Test that the endpoint 404's without the required query params. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400) def test_get_student_progress_url_nostudent(self): """ Test that the endpoint 400's when requesting an unknown email. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400) @attr('shard_1') class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test endpoints whereby instructors can change student grades. This includes resetting attempts and starting rescore tasks. This test does NOT test whether the actions had an effect on the database, that is the job of task tests and test_enrollment. """ @classmethod def setUpClass(cls): super(TestInstructorAPIRegradeTask, cls).setUpClass() cls.course = CourseFactory.create() cls.problem_location = msk_from_problem_urlname( cls.course.id, 'robot-some-problem-urlname' ) cls.problem_urlname = cls.problem_location.to_deprecated_string() def setUp(self): super(TestInstructorAPIRegradeTask, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.student = UserFactory() CourseEnrollment.enroll(self.student, self.course.id) self.module_to_reset = StudentModule.objects.create( student=self.student, course_id=self.course.id, module_state_key=self.problem_location, state=json.dumps({'attempts': 10}), ) def test_reset_student_attempts_deletall(self): """ Make sure no one can delete all students state on a problem. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'all_students': True, 'delete_module': True, }) self.assertEqual(response.status_code, 400) def test_reset_student_attempts_single(self): """ Test reset single student attempts. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # make sure problem attempts have been reset. changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk) self.assertEqual( json.loads(changed_module.state)['attempts'], 0 ) # mock out the function which should be called to execute the action. @patch.object(instructor_task.api, 'submit_reset_problem_attempts_for_all_students') def test_reset_student_attempts_all(self, act): """ Test reset all student attempts. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called) def test_reset_student_attempts_missingmodule(self): """ Test reset for non-existant problem. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': 'robot-not-a-real-module', 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400) def test_reset_student_attempts_delete(self): """ Test delete single student state. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 200) # make sure the module has been deleted self.assertEqual( StudentModule.objects.filter( student=self.module_to_reset.student, course_id=self.module_to_reset.course_id, # module_id=self.module_to_reset.module_id, ).count(), 0 ) def test_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400) @patch.object(instructor_task.api, 'submit_rescore_problem_for_student') def test_rescore_problem_single(self, act): """ Test rescoring of a single student. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called) @patch.object(instructor_task.api, 'submit_rescore_problem_for_student') def test_rescore_problem_single_from_uname(self, act): """ Test rescoring of a single student. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.username, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called) @patch.object(instructor_task.api, 'submit_rescore_problem_for_all_students') def test_rescore_problem_all(self, act): """ Test rescoring for all students. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called) @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) def test_course_has_entrance_exam_in_student_attempts_reset(self): """ Test course has entrance exam id set while resetting attempts""" url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, 'delete_module': False, }) self.assertEqual(response.status_code, 400) @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) def test_rescore_entrance_exam_with_invalid_exam(self): """ Test course has entrance exam id set while re-scoring. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400) @attr('shard_1') @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test endpoints whereby instructors can rescore student grades, reset student attempts and delete state for entrance exam. """ @classmethod def setUpClass(cls): super(TestEntranceExamInstructorAPIRegradeTask, cls).setUpClass() cls.course = CourseFactory.create( org='test_org', course='test_course', run='test_run', entrance_exam_id='i4x://{}/{}/chapter/Entrance_exam'.format('test_org', 'test_course') ) cls.course_with_invalid_ee = CourseFactory.create(entrance_exam_id='invalid_exam') with cls.store.bulk_operations(cls.course.id, emit_signals=False): cls.entrance_exam = ItemFactory.create( parent=cls.course, category='chapter', display_name='Entrance exam' ) subsection = ItemFactory.create( parent=cls.entrance_exam, category='sequential', display_name='Subsection 1' ) vertical = ItemFactory.create( parent=subsection, category='vertical', display_name='Vertical 1' ) cls.ee_problem_1 = ItemFactory.create( parent=vertical, category="problem", display_name="Exam Problem - Problem 1" ) cls.ee_problem_2 = ItemFactory.create( parent=vertical, category="problem", display_name="Exam Problem - Problem 2" ) def setUp(self): super(TestEntranceExamInstructorAPIRegradeTask, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) # Add instructor to invalid ee course CourseInstructorRole(self.course_with_invalid_ee.id).add_users(self.instructor) self.client.login(username=self.instructor.username, password='test') self.student = UserFactory() CourseEnrollment.enroll(self.student, self.course.id) ee_module_to_reset1 = StudentModule.objects.create( student=self.student, course_id=self.course.id, module_state_key=self.ee_problem_1.location, state=json.dumps({'attempts': 10, 'done': True}), ) ee_module_to_reset2 = StudentModule.objects.create( student=self.student, course_id=self.course.id, module_state_key=self.ee_problem_2.location, state=json.dumps({'attempts': 10, 'done': True}), ) self.ee_modules = [ee_module_to_reset1.module_state_key, ee_module_to_reset2.module_state_key] def test_reset_entrance_exam_student_attempts_deletall(self): """ Make sure no one can delete all students state on entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, 'delete_module': True, }) self.assertEqual(response.status_code, 400) def test_reset_entrance_exam_student_attempts_single(self): """ Test reset single student attempts for entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # make sure problem attempts have been reset. changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) for changed_module in changed_modules: self.assertEqual( json.loads(changed_module.state)['attempts'], 0 ) # mock out the function which should be called to execute the action. @patch.object(instructor_task.api, 'submit_reset_problem_attempts_in_entrance_exam') def test_reset_entrance_exam_all_student_attempts(self, act): """ Test reset all student attempts for entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called) def test_reset_student_attempts_invalid_entrance_exam(self): """ Test reset for invalid entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course_with_invalid_ee.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400) def test_entrance_exam_sttudent_delete_state(self): """ Test delete single student entrance exam state. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 200) # make sure the module has been deleted changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) self.assertEqual(changed_modules.count(), 0) def test_entrance_exam_delete_state_with_staff(self): """ Test entrance exam delete state failure with staff access. """ self.client.logout() staff_user = StaffFactory(course_key=self.course.id) self.client.login(username=staff_user.username, password='test') url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 403) def test_entrance_exam_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400) @patch.object(instructor_task.api, 'submit_rescore_entrance_exam_for_student') def test_rescore_entrance_exam_single_student(self, act): """ Test re-scoring of entrance exam for single student. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called) def test_rescore_entrance_exam_all_student(self): """ Test rescoring for all students. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, }) self.assertEqual(response.status_code, 200) def test_rescore_entrance_exam_all_student_and_single(self): """ Test re-scoring with both all students and single student parameters. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400) def test_rescore_entrance_exam_with_invalid_exam(self): """ Test re-scoring of entrance exam with invalid exam. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course_with_invalid_ee.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400) def test_list_entrance_exam_instructor_tasks_student(self): """ Test list task history for entrance exam AND student. """ # create a re-score entrance exam task url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # check response tasks = json.loads(response.content)['tasks'] self.assertEqual(len(tasks), 1) self.assertEqual(tasks[0]['status'], _('Complete')) def test_list_entrance_exam_instructor_tasks_all_student(self): """ Test list task history for entrance exam AND all student. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) # check response tasks = json.loads(response.content)['tasks'] self.assertEqual(len(tasks), 0) def test_list_entrance_exam_instructor_with_invalid_exam_key(self): """ Test list task history for entrance exam failure if course has invalid exam. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course_with_invalid_ee.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400) def test_skip_entrance_exam_student(self): """ Test skip entrance exam api for student. """ # create a re-score entrance exam task url = reverse('mark_student_can_skip_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # check response message = _('This student (%s) will skip the entrance exam.') % self.student.email self.assertContains(response, message) # post again with same student response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) # This time response message should be different message = _('This student (%s) is already allowed to skip the entrance exam.') % self.student.email self.assertContains(response, message) @attr('shard_1') @patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message')) @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False}) class TestInstructorSendEmail(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Checks that only instructors have access to email endpoints, and that these endpoints are only accessible with courses that actually exist, only with valid email messages. """ @classmethod def setUpClass(cls): super(TestInstructorSendEmail, cls).setUpClass() cls.course = CourseFactory.create() test_subject = u'\u1234 test subject' test_message = u'\u6824 test message' cls.full_test_message = { 'send_to': 'staff', 'subject': test_subject, 'message': test_message, } def setUp(self): super(TestInstructorSendEmail, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') def test_send_email_as_logged_in_instructor(self): url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, self.full_test_message) self.assertEqual(response.status_code, 200) def test_send_email_but_not_logged_in(self): self.client.logout() url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, self.full_test_message) self.assertEqual(response.status_code, 403) def test_send_email_but_not_staff(self): self.client.logout() student = UserFactory() self.client.login(username=student.username, password='test') url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, self.full_test_message) self.assertEqual(response.status_code, 403) def test_send_email_but_course_not_exist(self): url = reverse('send_email', kwargs={'course_id': 'GarbageCourse/DNE/NoTerm'}) response = self.client.post(url, self.full_test_message) self.assertNotEqual(response.status_code, 200) def test_send_email_no_sendto(self): url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'subject': 'test subject', 'message': 'test message', }) self.assertEqual(response.status_code, 400) def test_send_email_no_subject(self): url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'send_to': 'staff', 'message': 'test message', }) self.assertEqual(response.status_code, 400) def test_send_email_no_message(self): url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'send_to': 'staff', 'subject': 'test subject', }) self.assertEqual(response.status_code, 400) class MockCompletionInfo(object): """Mock for get_task_completion_info""" times_called = 0 def mock_get_task_completion_info(self, *args): # pylint: disable=unused-argument """Mock for get_task_completion_info""" self.times_called += 1 if self.times_called % 2 == 0: return True, 'Task Completed' return False, 'Task Errored In Some Way' @attr('shard_1') class TestInstructorAPITaskLists(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test instructor task list endpoint. """ class FakeTask(object): """ Fake task object """ FEATURES = [ 'task_type', 'task_input', 'task_id', 'requester', 'task_state', 'created', 'status', 'task_message', 'duration_sec' ] def __init__(self, completion): for feature in self.FEATURES: setattr(self, feature, 'expected') # created needs to be a datetime self.created = datetime.datetime(2013, 10, 25, 11, 42, 35) # set 'status' and 'task_message' attrs success, task_message = completion() if success: self.status = "Complete" else: self.status = "Incomplete" self.task_message = task_message # Set 'task_output' attr, which will be parsed to the 'duration_sec' attr. self.task_output = '{"duration_ms": 1035000}' self.duration_sec = 1035000 / 1000.0 def make_invalid_output(self): """Munge task_output to be invalid json""" self.task_output = 'HI MY NAME IS INVALID JSON' # This should be given the value of 'unknown' if the task output # can't be properly parsed self.duration_sec = 'unknown' def to_dict(self): """ Convert fake task to dictionary representation. """ attr_dict = {key: getattr(self, key) for key in self.FEATURES} attr_dict['created'] = attr_dict['created'].isoformat() return attr_dict @classmethod def setUpClass(cls): super(TestInstructorAPITaskLists, cls).setUpClass() cls.course = CourseFactory.create( entrance_exam_id='i4x://{}/{}/chapter/Entrance_exam'.format('test_org', 'test_course') ) cls.problem_location = msk_from_problem_urlname( cls.course.id, 'robot-some-problem-urlname' ) cls.problem_urlname = cls.problem_location.to_deprecated_string() def setUp(self): super(TestInstructorAPITaskLists, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.student = UserFactory() CourseEnrollment.enroll(self.student, self.course.id) self.module = StudentModule.objects.create( student=self.student, course_id=self.course.id, module_state_key=self.problem_location, state=json.dumps({'attempts': 10}), ) mock_factory = MockCompletionInfo() self.tasks = [self.FakeTask(mock_factory.mock_get_task_completion_info) for _ in xrange(7)] self.tasks[-1].make_invalid_output() @patch.object(instructor_task.api, 'get_running_instructor_tasks') def test_list_instructor_tasks_running(self, act): """ Test list of all running tasks. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks) @patch.object(instructor_task.api, 'get_instructor_task_history') def test_list_background_email_tasks(self, act): """Test list of background email tasks.""" act.return_value = self.tasks url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks) @patch.object(instructor_task.api, 'get_instructor_task_history') def test_list_instructor_tasks_problem(self, act): """ Test list task history for problem. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, { 'problem_location_str': self.problem_urlname, }) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks) @patch.object(instructor_task.api, 'get_instructor_task_history') def test_list_instructor_tasks_problem_student(self, act): """ Test list task history for problem AND student. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, { 'problem_location_str': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks) @attr('shard_1') @patch.object(instructor_task.api, 'get_instructor_task_history') class TestInstructorEmailContentList(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test the instructor email content history endpoint. """ @classmethod def setUpClass(cls): super(TestInstructorEmailContentList, cls).setUpClass() cls.course = CourseFactory.create() def setUp(self): super(TestInstructorEmailContentList, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') self.tasks = {} self.emails = {} self.emails_info = {} def setup_fake_email_info(self, num_emails, with_failures=False): """ Initialize the specified number of fake emails """ for email_id in range(num_emails): num_sent = random.randint(1, 15401) if with_failures: failed = random.randint(1, 15401) else: failed = 0 self.tasks[email_id] = FakeContentTask(email_id, num_sent, failed, 'expected') self.emails[email_id] = FakeEmail(email_id) self.emails_info[email_id] = FakeEmailInfo(self.emails[email_id], num_sent, failed) def get_matching_mock_email(self, **kwargs): """ Returns the matching mock emails for the given id """ email_id = kwargs.get('id', 0) return self.emails[email_id] def get_email_content_response(self, num_emails, task_history_request, with_failures=False): """ Calls the list_email_content endpoint and returns the repsonse """ self.setup_fake_email_info(num_emails, with_failures) task_history_request.return_value = self.tasks.values() url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info: mock_email_info.side_effect = self.get_matching_mock_email response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) return response def check_emails_sent(self, num_emails, task_history_request, with_failures=False): """ Tests sending emails with or without failures """ response = self.get_email_content_response(num_emails, task_history_request, with_failures) self.assertTrue(task_history_request.called) expected_email_info = [email_info.to_dict() for email_info in self.emails_info.values()] actual_email_info = json.loads(response.content)['emails'] self.assertEqual(len(actual_email_info), num_emails) for exp_email, act_email in zip(expected_email_info, actual_email_info): self.assertDictEqual(exp_email, act_email) self.assertEqual(expected_email_info, actual_email_info) def test_content_list_one_email(self, task_history_request): """ Test listing of bulk emails when email list has one email """ response = self.get_email_content_response(1, task_history_request) self.assertTrue(task_history_request.called) email_info = json.loads(response.content)['emails'] # Emails list should have one email self.assertEqual(len(email_info), 1) # Email content should be what's expected expected_message = self.emails[0].html_message returned_email_info = email_info[0] received_message = returned_email_info[u'email'][u'html_message'] self.assertEqual(expected_message, received_message) def test_content_list_no_emails(self, task_history_request): """ Test listing of bulk emails when email list empty """ response = self.get_email_content_response(0, task_history_request) self.assertTrue(task_history_request.called) email_info = json.loads(response.content)['emails'] # Emails list should be empty self.assertEqual(len(email_info), 0) def test_content_list_email_content_many(self, task_history_request): """ Test listing of bulk emails sent large amount of emails """ self.check_emails_sent(50, task_history_request) def test_list_email_content_error(self, task_history_request): """ Test handling of error retrieving email """ invalid_task = FakeContentTask(0, 0, 0, 'test') invalid_task.make_invalid_input() task_history_request.return_value = [invalid_task] url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) self.assertTrue(task_history_request.called) returned_email_info = json.loads(response.content)['emails'] self.assertEqual(len(returned_email_info), 1) returned_info = returned_email_info[0] for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']: self.assertEqual(returned_info[info], None) def test_list_email_with_failure(self, task_history_request): """ Test the handling of email task that had failures """ self.check_emails_sent(1, task_history_request, True) def test_list_many_emails_with_failures(self, task_history_request): """ Test the handling of many emails with failures """ self.check_emails_sent(50, task_history_request, True) def test_list_email_with_no_successes(self, task_history_request): task_info = FakeContentTask(0, 0, 10, 'expected') email = FakeEmail(0) email_info = FakeEmailInfo(email, 0, 10) task_history_request.return_value = [task_info] url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info: mock_email_info.return_value = email response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) self.assertTrue(task_history_request.called) returned_info_list = json.loads(response.content)['emails'] self.assertEqual(len(returned_info_list), 1) returned_info = returned_info_list[0] expected_info = email_info.to_dict() self.assertDictEqual(expected_info, returned_info) @attr('shard_1') class TestInstructorAPIHelpers(TestCase): """ Test helpers for instructor.api """ def test_split_input_list(self): strings = [] lists = [] strings.append( "Lorem@ipsum.dolor, sit@amet.consectetur\nadipiscing@elit.Aenean\r convallis@at.lacus\r, ut@lacinia.Sed") lists.append(['Lorem@ipsum.dolor', 'sit@amet.consectetur', 'adipiscing@elit.Aenean', 'convallis@at.lacus', 'ut@lacinia.Sed']) for (stng, lst) in zip(strings, lists): self.assertEqual(_split_input_list(stng), lst) def test_split_input_list_unicode(self): self.assertEqual(_split_input_list('robot@robot.edu, robot2@robot.edu'), ['robot@robot.edu', 'robot2@robot.edu']) self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'), ['robot@robot.edu', 'robot2@robot.edu']) self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'), [u'robot@robot.edu', 'robot2@robot.edu']) scary_unistuff = unichr(40960) + u'abcd' + unichr(1972) self.assertEqual(_split_input_list(scary_unistuff), [scary_unistuff]) def test_msk_from_problem_urlname(self): course_id = SlashSeparatedCourseKey('MITx', '6.002x', '2013_Spring') name = 'L2Node1' output = 'i4x://MITx/6.002x/problem/L2Node1' self.assertEqual(msk_from_problem_urlname(course_id, name).to_deprecated_string(), output) @raises(ValueError) def test_msk_from_problem_urlname_error(self): args = ('notagoodcourse', 'L2Node1') msk_from_problem_urlname(*args) def get_extended_due(course, unit, user): """ Gets the overridden due date for the given user on the given unit. Returns `None` if there is no override set. """ try: override = StudentFieldOverride.objects.get( course_id=course.id, student=user, location=unit.location, field='due' ) return DATE_FIELD.from_json(json.loads(override.value)) except StudentFieldOverride.DoesNotExist: return None @attr('shard_1') class TestDueDateExtensions(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Test data dumps for reporting. """ @classmethod def setUpClass(cls): super(TestDueDateExtensions, cls).setUpClass() cls.course = CourseFactory.create() cls.due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc) with cls.store.bulk_operations(cls.course.id, emit_signals=False): cls.week1 = ItemFactory.create(due=cls.due) cls.week2 = ItemFactory.create(due=cls.due) cls.week3 = ItemFactory.create() # No due date cls.course.children = [ cls.week1.location.to_deprecated_string(), cls.week2.location.to_deprecated_string(), cls.week3.location.to_deprecated_string() ] cls.homework = ItemFactory.create( parent_location=cls.week1.location, due=cls.due ) cls.week1.children = [cls.homework.location.to_deprecated_string()] def setUp(self): """ Fixtures. """ super(TestDueDateExtensions, self).setUp() user1 = UserFactory.create() StudentModule( state='{}', student_id=user1.id, course_id=self.course.id, module_state_key=self.week1.location).save() StudentModule( state='{}', student_id=user1.id, course_id=self.course.id, module_state_key=self.week2.location).save() StudentModule( state='{}', student_id=user1.id, course_id=self.course.id, module_state_key=self.week3.location).save() StudentModule( state='{}', student_id=user1.id, course_id=self.course.id, module_state_key=self.homework.location).save() user2 = UserFactory.create() StudentModule( state='{}', student_id=user2.id, course_id=self.course.id, module_state_key=self.week1.location).save() StudentModule( state='{}', student_id=user2.id, course_id=self.course.id, module_state_key=self.homework.location).save() user3 = UserFactory.create() StudentModule( state='{}', student_id=user3.id, course_id=self.course.id, module_state_key=self.week1.location).save() StudentModule( state='{}', student_id=user3.id, course_id=self.course.id, module_state_key=self.homework.location).save() self.user1 = user1 self.user2 = user2 self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') def test_change_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '12/30/2013 00:00' }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc), get_extended_due(self.course, self.week1, self.user1)) def test_change_to_invalid_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '01/01/2009 00:00' }) self.assertEqual(response.status_code, 400, response.content) self.assertEqual( None, get_extended_due(self.course, self.week1, self.user1) ) def test_change_nonexistent_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week3.location.to_deprecated_string(), 'due_datetime': '12/30/2013 00:00' }) self.assertEqual(response.status_code, 400, response.content) self.assertEqual( None, get_extended_due(self.course, self.week3, self.user1) ) def test_reset_date(self): self.test_change_due_date() url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual( None, get_extended_due(self.course, self.week1, self.user1) ) def test_reset_nonexistent_extension(self): url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) self.assertEqual(response.status_code, 400, response.content) @SharedModuleStoreTestCase.modifies_courseware def test_reset_extension_to_deleted_date(self): """ Test that we can delete a due date extension after deleting the normal due date, without causing an error. """ self.test_change_due_date() self.week1.due = None self.week1 = self.store.update_item(self.week1, self.user1.id) # Now, week1's normal due date is deleted but the extension still exists. url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual( None, get_extended_due(self.course, self.week1, self.user1) ) def test_show_unit_extensions(self): self.test_change_due_date() url = reverse('show_unit_extensions', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {'url': self.week1.location.to_deprecated_string()}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(json.loads(response.content), { u'data': [{u'Extended Due Date': u'2013-12-30 00:00', u'Full Name': self.user1.profile.name, u'Username': self.user1.username}], u'header': [u'Username', u'Full Name', u'Extended Due Date'], u'title': u'Users with due date extensions for %s' % self.week1.display_name}) def test_show_student_extensions(self): self.test_change_due_date() url = reverse('show_student_extensions', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {'student': self.user1.username}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(json.loads(response.content), { u'data': [{u'Extended Due Date': u'2013-12-30 00:00', u'Unit': self.week1.display_name}], u'header': [u'Unit', u'Extended Due Date'], u'title': u'Due date extensions for %s (%s)' % ( self.user1.profile.name, self.user1.username)}) @attr('shard_1') class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): """ Test data dumps for issued certificates. """ @classmethod def setUpClass(cls): super(TestCourseIssuedCertificatesData, cls).setUpClass() cls.course = CourseFactory.create() def setUp(self): super(TestCourseIssuedCertificatesData, self).setUp() self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') def generate_certificate(self, course_id, mode, status): """ Generate test certificate """ test_user = UserFactory() GeneratedCertificateFactory.create( user=test_user, course_id=course_id, mode=mode, status=status ) def test_certificates_features_against_status(self): """ Test certificates with status 'downloadable' should be in the response. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 0) # Certificates with status 'downloadable' should be in response. self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 1) def test_certificates_features_group_by_mode(self): """ Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 1) # retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode. certificate = res_json['certificates'][0] self.assertEqual(certificate.get('total_issued_certificate'), 3) self.assertEqual(certificate.get('mode'), 'honor') self.assertEqual(certificate.get('course_id'), str(self.course.id)) # Now generating downloadable certificates with 'verified' mode for __ in xrange(certificate_count): self.generate_certificate( course_id=self.course.id, mode='verified', status=CertificateStatuses.downloadable ) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) # total certificate count should be 2 for 'verified' mode. self.assertEqual(len(res_json['certificates']), 2) # retrieve the second certificate from the list certificate = res_json['certificates'][1] self.assertEqual(certificate.get('total_issued_certificate'), 3) self.assertEqual(certificate.get('mode'), 'verified') def test_certificates_features_csv(self): """ Test for certificate csv features. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) url += '?csv=true' # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) current_date = datetime.date.today().strftime("%B %d, %Y") response = self.client.get(url) self.assertEqual(response['Content-Type'], 'text/csv') self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv')) self.assertEqual( response.content.strip(), '"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"' + str(self.course.id) + '","honor","3","' + current_date + '"' ) @attr('shard_1') @override_settings(REGISTRATION_CODE_LENGTH=8) class TestCourseRegistrationCodes(SharedModuleStoreTestCase): """ Test data dumps for E-commerce Course Registration Codes. """ @classmethod def setUpClass(cls): super(TestCourseRegistrationCodes, cls).setUpClass() cls.course = CourseFactory.create() cls.url = reverse( 'generate_registration_codes', kwargs={'course_id': cls.course.id.to_deprecated_string()} ) def setUp(self): """ Fixtures. """ super(TestCourseRegistrationCodes, self).setUp() CourseModeFactory.create(course_id=self.course.id, min_price=50) self.instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=self.instructor.username, password='test') CourseSalesAdminRole(self.course.id).add_users(self.instructor) data = { 'total_registration_codes': 12, 'company_name': 'Test Group', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(self.url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) for i in range(5): order = Order(user=self.instructor, status='purchased') order.save() # Spent(used) Registration Codes for i in range(5): i += 1 registration_code_redemption = RegistrationCodeRedemption( registration_code_id=i, redeemed_by=self.instructor ) registration_code_redemption.save() @override_settings(FINANCE_EMAIL='finance@example.com') def test_finance_email_in_recipient_list_when_generating_registration_codes(self): """ Test to verify that the invoice will also be sent to the FINANCE_EMAIL when generating registration codes """ url_reg_code = reverse('generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = { 'total_registration_codes': 5, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 121.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': 'True' } response = self.client.post(url_reg_code, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') # check for the last mail.outbox, The FINANCE_EMAIL has been appended at the # very end, when generating registration codes self.assertEqual(mail.outbox[-1].to[0], 'finance@example.com') def test_user_invoice_copy_preference(self): """ Test to remember user invoice copy preference """ url_reg_code = reverse('generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = { 'total_registration_codes': 5, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 121.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': 'True' } # user invoice copy preference will be saved in api user preference; model response = self.client.post(url_reg_code, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') # get user invoice copy preference. url_user_invoice_preference = reverse('get_user_invoice_preference', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url_user_invoice_preference, data) result = json.loads(response.content) self.assertEqual(result['invoice_copy'], True) # updating the user invoice copy preference during code generation flow data['invoice'] = '' response = self.client.post(url_reg_code, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') # get user invoice copy preference. url_user_invoice_preference = reverse('get_user_invoice_preference', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url_user_invoice_preference, data) result = json.loads(response.content) self.assertEqual(result['invoice_copy'], False) def test_generate_course_registration_codes_csv(self): """ Test to generate a response of all the generated course registration codes """ url = reverse('generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = { 'total_registration_codes': 15, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 17) def test_generate_course_registration_with_redeem_url_codes_csv(self): """ Test to generate a response of all the generated course registration codes """ url = reverse('generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = { 'total_registration_codes': 15, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 17) rows = body.split('\n') index = 1 while index < len(rows): if rows[index]: row_data = rows[index].split(',') code = row_data[0].replace('"', '') self.assertTrue(row_data[1].startswith('"http') and row_data[1].endswith('/shoppingcart/register/redeem/{0}/"'.format(code))) index += 1 @patch.object(instructor.views.api, 'random_code_generator', Mock(side_effect=['first', 'second', 'third', 'fourth'])) def test_generate_course_registration_codes_matching_existing_coupon_code(self): """ Test the generated course registration code is already in the Coupon Table """ url = reverse('generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) coupon = Coupon(code='first', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor) coupon.save() data = { 'total_registration_codes': 3, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 5) # 1 for headers, 1 for new line at the end and 3 for the actual data @patch.object(instructor.views.api, 'random_code_generator', Mock(side_effect=['first', 'first', 'second', 'third'])) def test_generate_course_registration_codes_integrity_error(self): """ Test for the Integrity error against the generated code """ url = reverse('generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = { 'total_registration_codes': 2, 'company_name': 'Test Group', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 4) def test_spent_course_registration_codes_csv(self): """ Test to generate a response of all the spent course registration codes """ url = reverse('spent_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = {'spent_company_name': ''} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 7) generate_code_url = reverse( 'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = { 'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'unit_price': 122.45, 'company_contact_email': 'Test@company.com', 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) for i in range(9): order = Order(user=self.instructor, status='purchased') order.save() # Spent(used) Registration Codes for i in range(9): i += 13 registration_code_redemption = RegistrationCodeRedemption( registration_code_id=i, redeemed_by=self.instructor ) registration_code_redemption.save() data = {'spent_company_name': 'Group Alpha'} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 11) def test_active_course_registration_codes_csv(self): """ Test to generate a response of all the active course registration codes """ url = reverse('active_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = {'active_company_name': ''} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 9) generate_code_url = reverse( 'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = { 'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) data = {'active_company_name': 'Group Alpha'} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 11) def test_get_all_course_registration_codes_csv(self): """ Test to generate a response of all the course registration codes """ url = reverse( 'get_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = {'download_company_name': ''} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 14) generate_code_url = reverse( 'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = { 'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) data = {'download_company_name': 'Group Alpha'} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) self.assertEqual(len(body.split('\n')), 11) def test_pdf_file_throws_exception(self): """ test to mock the pdf file generation throws an exception when generating registration codes. """ generate_code_url = reverse( 'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = { 'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': '' } with patch.object(PDFInvoice, 'generate_pdf', side_effect=Exception): response = self.client.post(generate_code_url, data) self.assertEqual(response.status_code, 200, response.content) def test_get_codes_with_sale_invoice(self): """ Test to generate a response of all the course registration codes """ generate_code_url = reverse( 'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = { 'total_registration_codes': 5.5, 'company_name': 'Group Invoice', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 122.45, 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': True } response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 200, response.content) url = reverse('get_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}) data = {'download_company_name': 'Group Invoice'} response = self.client.post(url, data) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_CSV_HEADER)) def test_with_invalid_unit_price(self): """ Test to generate a response of all the course registration codes """ generate_code_url = reverse( 'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) data = { 'total_registration_codes': 10, 'company_name': 'Group Invoice', 'company_contact_name': 'Test@company.com', 'company_contact_email': 'Test@company.com', 'unit_price': 'invalid', 'recipient_name': 'Test123', 'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '', 'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': True } response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'}) self.assertEqual(response.status_code, 400, response.content) self.assertIn('Could not parse amount as', response.content) def test_get_historical_coupon_codes(self): """ Test to download a response of all the active coupon codes """ get_coupon_code_url = reverse( 'get_coupon_codes', kwargs={'course_id': self.course.id.to_deprecated_string()} ) for i in range(10): coupon = Coupon( code='test_code{0}'.format(i), description='test_description', course_id=self.course.id, percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True ) coupon.save() #now create coupons with the expiration dates for i in range(5): coupon = Coupon( code='coupon{0}'.format(i), description='test_description', course_id=self.course.id, percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True, expiration_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2) ) coupon.save() response = self.client.get(get_coupon_code_url) self.assertEqual(response.status_code, 200, response.content) # filter all the coupons for coupon in Coupon.objects.all(): self.assertIn( '"{coupon_code}","{course_id}","{discount}","{description}","{expiration_date}","{is_active}",' '"{code_redeemed_count}","{total_discounted_seats}","{total_discounted_amount}"'.format( coupon_code=coupon.code, course_id=coupon.course_id, discount=coupon.percentage_discount, description=coupon.description, expiration_date=coupon.display_expiry_date, is_active=coupon.is_active, code_redeemed_count="0", total_discounted_seats="0", total_discounted_amount="0", ), response.content ) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith(EXPECTED_COUPON_CSV_HEADER)) @attr('shard_1') class TestBulkCohorting(SharedModuleStoreTestCase): """ Test adding users to cohorts in bulk via CSV upload. """ @classmethod def setUpClass(cls): super(TestBulkCohorting, cls).setUpClass() cls.course = CourseFactory.create() def setUp(self): super(TestBulkCohorting, self).setUp() self.staff_user = StaffFactory(course_key=self.course.id) self.non_staff_user = UserFactory.create() self.tempdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tempdir) def call_add_users_to_cohorts(self, csv_data, suffix='.csv', method='POST'): """ Call `add_users_to_cohorts` with a file generated from `csv_data`. """ # this temporary file will be removed in `self.tearDown()` __, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir) with open(file_name, 'w') as file_pointer: file_pointer.write(csv_data.encode('utf-8')) with open(file_name, 'r') as file_pointer: url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)}) if method == 'POST': return self.client.post(url, {'uploaded-file': file_pointer}) elif method == 'GET': return self.client.get(url, {'uploaded-file': file_pointer}) def expect_error_on_file_content(self, file_content, error, file_suffix='.csv'): """ Verify that we get the error we expect for a given file input. """ self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts(file_content, suffix=file_suffix) self.assertEqual(response.status_code, 400) result = json.loads(response.content) self.assertEqual(result['error'], error) def verify_success_on_file_content(self, file_content, mock_store_upload, mock_cohort_task): """ Verify that `addd_users_to_cohorts` successfully validates the file content, uploads the input file, and triggers the background task. """ mock_store_upload.return_value = (None, 'fake_file_name.csv') self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts(file_content) self.assertEqual(response.status_code, 204) self.assertTrue(mock_store_upload.called) self.assertTrue(mock_cohort_task.called) def test_no_cohort_field(self): """ Verify that we get a descriptive verification error when we haven't included a cohort field in the uploaded CSV. """ self.expect_error_on_file_content( 'username,email\n', "The file must contain a 'cohort' column containing cohort names." ) def test_no_username_or_email_field(self): """ Verify that we get a descriptive verification error when we haven't included a username or email field in the uploaded CSV. """ self.expect_error_on_file_content( 'cohort\n', "The file must contain a 'username' column, an 'email' column, or both." ) def test_empty_csv(self): """ Verify that we get a descriptive verification error when we haven't included any data in the uploaded CSV. """ self.expect_error_on_file_content( '', "The file must contain a 'cohort' column containing cohort names." ) def test_wrong_extension(self): """ Verify that we get a descriptive verification error when we haven't uploaded a file with a '.csv' extension. """ self.expect_error_on_file_content( '', "The file must end with the extension '.csv'.", file_suffix='.notcsv' ) def test_non_staff_no_access(self): """ Verify that we can't access the view when we aren't a staff user. """ self.client.login(username=self.non_staff_user.username, password='test') response = self.call_add_users_to_cohorts('') self.assertEqual(response.status_code, 403) def test_post_only(self): """ Verify that we can't call the view when we aren't using POST. """ self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts('', method='GET') self.assertEqual(response.status_code, 405) @patch('instructor.views.api.instructor_task.api.submit_cohort_students') @patch('instructor.views.api.store_uploaded_file') def test_success_username(self, mock_store_upload, mock_cohort_task): """ Verify that we store the input CSV and call a background task when the CSV has username and cohort columns. """ self.verify_success_on_file_content( 'username,cohort\nfoo_username,bar_cohort', mock_store_upload, mock_cohort_task ) @patch('instructor.views.api.instructor_task.api.submit_cohort_students') @patch('instructor.views.api.store_uploaded_file') def test_success_email(self, mock_store_upload, mock_cohort_task): """ Verify that we store the input CSV and call the cohorting background task when the CSV has email and cohort columns. """ self.verify_success_on_file_content( 'email,cohort\nfoo_email,bar_cohort', mock_store_upload, mock_cohort_task ) @patch('instructor.views.api.instructor_task.api.submit_cohort_students') @patch('instructor.views.api.store_uploaded_file') def test_success_username_and_email(self, mock_store_upload, mock_cohort_task): """ Verify that we store the input CSV and call the cohorting background task when the CSV has username, email and cohort columns. """ self.verify_success_on_file_content( 'username,email,cohort\nfoo_username,bar_email,baz_cohort', mock_store_upload, mock_cohort_task ) @patch('instructor.views.api.instructor_task.api.submit_cohort_students') @patch('instructor.views.api.store_uploaded_file') def test_success_carriage_return(self, mock_store_upload, mock_cohort_task): """ Verify that we store the input CSV and call the cohorting background task when lines in the CSV are delimited by carriage returns. """ self.verify_success_on_file_content( 'username,email,cohort\rfoo_username,bar_email,baz_cohort', mock_store_upload, mock_cohort_task ) @patch('instructor.views.api.instructor_task.api.submit_cohort_students') @patch('instructor.views.api.store_uploaded_file') def test_success_carriage_return_line_feed(self, mock_store_upload, mock_cohort_task): """ Verify that we store the input CSV and call the cohorting background task when lines in the CSV are delimited by carriage returns and line feeds. """ self.verify_success_on_file_content( 'username,email,cohort\r\nfoo_username,bar_email,baz_cohort', mock_store_upload, mock_cohort_task )
mstriemer/addons-server
refs/heads/master
src/olympia/translations/__init__.py
18
from django.conf import settings from django.utils.translation import trans_real from jinja2.filters import do_dictsort LOCALES = [(trans_real.to_locale(k).replace('_', '-'), v) for k, v in do_dictsort(settings.LANGUAGES)]
lip6-mptcp/wireshark-mptcp
refs/heads/mptcp_final
help/faq.py
5
#!/usr/bin/env python # # faq.py # # Routines to assemble a FAQ list for the Wireshark web site. # Questions and answer content can be found below. Section and # question numbers will be automatically generated. # # Wireshark - Network traffic analyzer # By Gerald Combs <gerald@wireshark.org> # Copyright 1998 Gerald Combs # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import sys import string class faq_section: def __init__(self, name, secnum): self.name = name self.secnum = secnum self.qa = [] self.subsecs = [] def add_qa(self, question, answer, tag): q_num = len(self.qa) + 1 q_id = "%s.%d" % (self.get_num_string(), q_num) self.qa.append( (q_id, question, answer, tag) ) def get_all_qa(self): return self.qa def add_subsec(self, subsec): self.subsecs.append(subsec) def get_all_subsecs(self): return self.subsecs def get_num_string(self): return "%d" % (self.secnum) def get_name(self): return self.name def get_num_name(self): return "%s. %s" % (self.get_num_string(), self.name) def get_header_level(self): return 3 def print_index(self): print(("<a href=#sec%s><h%d>%s:</h%d></a>\n" % (self.get_num_string(), self.get_header_level(), self.get_num_name(), self.get_header_level()))) for qa in self.qa: id = qa[0] question = qa[1] print('<p class="faq_q">') print(('<a class="faq_qnum" href=#q%s>%s %s</a>\n' % (id, id, question))) print('</p>') for subsec in self.subsecs: subsec.print_index() def print_contents(self): # Table header print((""" <h%d id="sec%s">%s</h%d> """ % (self.get_header_level(), self.get_num_string(), self.get_num_name(), self.get_header_level()))) # Questions and Answers for qa in self.qa: id = qa[0] question = qa[1] answer = qa[2] tag = qa[3] print('<p class="faq_q">') if tag is not None: print(('<span id=%s></span>' % (tag))) print(('<a href=#q%s class="faq_qnum" id=q%s>Q %s: %s</a>' % (id, id, id, question))) print('</p>') print('<p class="faq_a">') print('<span class="faq_anum">A:</span>\n') print(answer) print('</p>') # Subsections for subsec in self.subsecs: subsec.print_contents() # Table footer print("") class faq_subsection(faq_section): def __init__(self, name, secnum, subsecnum): self.name = name self.secnum = secnum self.subsecnum = subsecnum self.qa = [] self.subsecs = [] def get_num_string(self): return "%d.%d" % (self.secnum, self.subsecnum) def get_header_level(self): return 2 class faq_subsubsection(faq_section): def __init__(self, name, secnum, subsecnum, subsubsecnum): self.name = name self.secnum = secnum self.subsecnum = subsecnum self.subsubsecnum = subsubsecnum self.qa = [] self.subsecs = [] def get_num_string(self): return "%d.%d.%d" % (self.secnum, self.subsecnum, self.subsubsecnum) def get_header_level(self): return 2 sec_num = 0 subsec_num = 0 subsubsec_num = 0 sections = [] current_section = None parent_section = None grandparent_section = None current_question = None current_tag = None # Make a URL of itself def selflink(text): return "<a href=\"%s\">%s</a>" % (text, text) # Add a section def section(name): global sec_num global subsec_num global subsubsec_num global current_section global grandparent_section assert not current_question sec_num = sec_num + 1 subsec_num = 0 subsubsec_num = 0 sec = faq_section(name, sec_num) sections.append(sec) current_section = sec grandparent_section = sec # Add a subsection def subsection(name): global subsec_num global subsubsec_num global current_section global parent_section global grandparent_section assert not current_question subsec_num = subsec_num + 1 subsubsec_num = 0 sec = faq_subsection(name, sec_num, subsec_num) grandparent_section.add_subsec(sec) current_section = sec parent_section = sec # Add a subsubsection def subsubsection(name): global subsubsec_num global current_section global parent_section assert not current_question subsubsec_num = subsubsec_num + 1 sec = faq_subsubsection(name, sec_num, subsec_num, subsubsec_num) parent_section.add_subsec(sec) current_section = sec # Add a question def question(text, tag=None): global current_question global current_tag assert current_section assert not current_question assert not current_tag current_question = text current_tag = tag # Add an answer def answer(text): global current_question global current_tag assert current_section assert current_question current_section.add_qa(current_question, text, current_tag) current_question = None current_tag = None # Create the index def create_index(): print(""" <h1 id="index">Index</h1> """) for sec in sections: sec.print_index() print(""" """) # Print result def create_output(header='', footer=''): print(header) create_index() for sec in sections: sec.print_contents() print(footer) def main(): header = '''\ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Wireshark Frequently Asked Questions</title> </head> <body> ''' footer = '''\ </body> </html> ''' if len(sys.argv) > 1 and sys.argv[1] == '-b': # Only print the document body header = '' footer = '' create_output(header, footer) ################################################################# section("General Questions") ################################################################# question("What is Wireshark?") answer(""" Wireshark&#174; is a network protocol analyzer. It lets you capture and interactively browse the traffic running on a computer network. It has a rich and powerful feature set and is world's most popular tool of its kind. It runs on most computing platforms including Windows, OS X, Linux, and UNIX. Network professionals, security experts, developers, and educators around the world use it regularly. It is freely available as open source, and is released under the GNU General Public License version 2. <br> It is developed and maintained by a global team of protocol experts, and it is an example of a <a href="https://en.wikipedia.org/wiki/Disruptive_technology">disruptive technology</a>. <br> Wireshark used to be known as Ethereal&#174;. See the next question for details about the name change. If you're still using Ethereal, it is strongly recommended that you upgrade to Wireshark as Ethereal is unsupported and has known security vulnerabilities. <br> For more information, please see the <a href="https://www.wireshark.org/about.html">About Wireshark</a> page. """) question("What's up with the name change? Is Wireshark a fork?") answer(""" In May of 2006, Gerald Combs (the original author of Ethereal) went to work for CACE Technologies (best known for WinPcap). Unfortunately, he had to leave the Ethereal trademarks behind. <br> This left the project in an awkward position. The only reasonable way to ensure the continued success of the project was to change the name. This is how Wireshark was born. <br> Wireshark is almost (but not quite) a fork. Normally a "fork" of an open source project results in two names, web sites, development teams, support infrastructures, etc. This is the case with Wireshark except for one notable exception -- every member of the core development team is now working on Wireshark. There has been no active development on Ethereal since the name change. Several parts of the Ethereal web site (such as the mailing lists, source code repository, and build farm) have gone offline. <br> More information on the name change can be found here: </p> <ul class="item_list"> <li><a href="http://www.prweb.com/releases/2006/6/prweb396098.htm">Original press release</a> <li><a href="http://archive09.linux.com/articles/54968">NewsForge article</a> <li>Many other articles in <a href="https://www.wireshark.org/bibliography.html">our bibliography</a> </ul> <p> """) question("Where can I get help?") answer(""" Community support is available on the <a href="https://ask.wireshark.org/">Q&amp;A site</a> and on the wireshark-users mailing list. Subscription information and archives for all of Wireshark's mailing lists can be found at %s. An IRC channel dedicated to Wireshark can be found at %s. <br> Self-paced and instructor-led training is available at <a href="http://www.wiresharktraining.com">Wireshark University</a>. Wireshark University also offers certification via the Wireshark Certified Network Analyst program. """ % (selflink("https://www.wireshark.org/mailman/listinfo"), selflink("irc://irc.freenode.net/wireshark") )) question("What kind of shark is Wireshark?") answer(""" <i>carcharodon photoshopia</i>. """) question("How is Wireshark pronounced, spelled and capitalized?") answer(""" Wireshark is pronounced as the word <i>wire</i> followed immediately by the word <i>shark</i>. Exact pronunciation and emphasis may vary depending on your locale (e.g. Arkansas). <br> It's spelled with a capital <i>W</i>, followed by a lower-case <i>ireshark</i>. It is not a CamelCase word, i.e., <i>WireShark</i> is incorrect. """) question("How much does Wireshark cost?", "but_thats_not_all") answer(""" Wireshark is "free software"; you can download it without paying any license fee. The version of Wireshark you download isn't a "demo" version, with limitations not present in a "full" version; it <em>is</em> the full version. <br> The license under which Wireshark is issued is <a href="https://www.gnu.org/licenses/gpl-2.0.html">the GNU General Public License version 2</a>. See <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html">the GNU GPL FAQ</a> for some more information. """) question("But I just paid someone on eBay for a copy of Wireshark! Did I get ripped off?") answer(""" That depends. Did they provide any sort of value-added product or service, such as installation support, installation media, training, trace file analysis, or funky-colored shark-themed socks? Probably not. <br> Wireshark is <a href="https://www.wireshark.org/download.html">available for anyone to download, absolutely free, at any time</a>. Paying for a copy implies that you should get something for your money. """) question("Can I use Wireshark commercially?") answer(""" Yes, if, for example, you mean "I work for a commercial organization; can I use Wireshark to capture and analyze network traffic in our company's networks or in our customer's networks?" <br> If you mean "Can I use Wireshark as part of my commercial product?", see <a href="#derived_work_gpl">the next entry in the FAQ</a>. """) question("Can I use Wireshark as part of my commercial product?", "derived_work_gpl") answer(""" As noted, Wireshark is licensed under <a href="https://www.gnu.org/licenses/gpl-2.0.html">the GNU General Public License, version 2</a>. The GPL imposes conditions on your use of GPL'ed code in your own products; you cannot, for example, make a "derived work" from Wireshark, by making modifications to it, and then sell the resulting derived work and not allow recipients to give away the resulting work. You must also make the changes you've made to the Wireshark source available to all recipients of your modified version; those changes must also be licensed under the terms of the GPL. See the <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html">GPL FAQ</a> for more details; in particular, note the answer to <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLCommercially">the question about modifying a GPLed program and selling it commercially</a>, and <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#LinkingWithGPL">the question about linking GPLed code with other code to make a proprietary program</a>. <br> You can combine a GPLed program such as Wireshark and a commercial program as long as they communicate "at arm's length", as per <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLInProprietarySystem">this item in the GPL FAQ</a>. <br> We recommend keeping Wireshark and your product completely separate, communicating over sockets or pipes. If you're loading any part of Wireshark as a DLL, you're probably doing it wrong. """) question("What protocols are currently supported?") answer(""" There are currently hundreds of supported protocols and media. Details can be found in the <a href="https://www.wireshark.org/docs/man-pages/wireshark.html">wireshark(1)</a> man page. """) question("Are there any plans to support {your favorite protocol}?") answer(""" Support for particular protocols is added to Wireshark as a result of people contributing that support; no formal plans for adding support for particular protocols in particular future releases exist. """) question("""Can Wireshark read capture files from {your favorite network analyzer}?""") answer(""" Support for particular capture file formats is added to Wireshark as a result of people contributing that support; no formal plans for adding support for particular capture file formats in particular future releases exist. <br> If a network analyzer writes out files in a format already supported by Wireshark (e.g., in libpcap format), Wireshark may already be able to read them, unless the analyzer has added its own proprietary extensions to that format. <br> If a network analyzer writes out files in its own format, or has added proprietary extensions to another format, in order to make Wireshark read captures from that network analyzer, we would either have to have a specification for the file format, or the extensions, sufficient to give us enough information to read the parts of the file relevant to Wireshark, or would need at least one capture file in that format <strong>AND</strong> a detailed textual analysis of the packets in that capture file (showing packet time stamps, packet lengths, and the top-level packet header) in order to reverse-engineer the file format. <br> Note that there is no guarantee that we will be able to reverse-engineer a capture file format. """) question("What devices can Wireshark use to capture packets?") answer(""" Wireshark can read live data from Ethernet, Token-Ring, FDDI, serial (PPP and SLIP) (if the OS on which it's running allows Wireshark to do so), 802.11 wireless LAN (if the OS on which it's running allows Wireshark to do so), ATM connections (if the OS on which it's running allows Wireshark to do so), and the "any" device supported on Linux by recent versions of libpcap. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/NetworkMedia">the list of supported capture media on various OSes</a> for details (several items in there say "Unknown", which doesn't mean "Wireshark can't capture on them", it means "we don't know whether it can capture on them"; we expect that it will be able to capture on many of them, but we haven't tried it ourselves - if you try one of those types and it works, please update the wiki page accordingly. <br> It can also read a variety of capture file formats, including: </p> <ul> <li> AG Group/WildPackets/Savvius EtherPeek/TokenPeek/AiroPeek/EtherHelp/Packet Grabber captures <li> AIX's iptrace captures <li> Accellent's 5Views LAN agent output <li> Cinco Networks NetXRay captures <li> Cisco Secure Intrusion Detection System IPLog output <li> CoSine L2 debug output <li> DBS Etherwatch VMS text output <li> Endace Measurement Systems' ERF format captures <li> EyeSDN USB S0 traces <li> HP-UX nettl captures <li> ISDN4BSD project i4btrace captures <li> Linux Bluez Bluetooth stack hcidump -w traces <li> Lucent/Ascend router debug output <li> Microsoft Network Monitor captures <li> Network Associates Windows-based Sniffer captures <li> Network General/Network Associates DOS-based Sniffer (compressed or uncompressed) captures <li> Network Instruments Observer version 9 captures <li> Novell LANalyzer captures <li> RADCOM's WAN/LAN analyzer captures <li> Shomiti/Finisar Surveyor captures <li> Toshiba's ISDN routers dump output <li> VMS TCPIPtrace/TCPtrace/UCX$TRACE output <li> Visual Networks' Visual UpTime traffic capture <li> libpcap, tcpdump and various other tools using tcpdump's capture format <li> snoop and atmsnoop output </ul> <p> so that it can read traces from various network types, as captured by other applications or equipment, even if it cannot itself capture on those network types. """) question(""" Does Wireshark work on Windows Vista or Windows Server 2008? """) answer(""" Yes, but if you want to capture packets as a normal user, you must make sure npf.sys is loaded. Wireshark's installer enables this by default. This is not a concern if you run Wireshark as Administrator, but this is discouraged. See the <a href="https://wiki.wireshark.org/CaptureSetup/CapturePrivileges#windows">CapturePrivileges</a> page on the wiki for more details. """) ################################################################# section("Installing Wireshark") ################################################################# question("""I installed the Wireshark RPM (or other package); why did it install TShark but not Wireshark?""") answer(""" Many distributions have separate Wireshark packages, one for non-GUI components such as TShark, editcap, dumpcap, etc. and one for the GUI. If this is the case on your system, there's probably a separate package named <code>wireshark-gnome</code> or <code>wireshark-gtk+</code>. Find it and install it. """) ################################################################# section("Building Wireshark") ################################################################# question("""I have libpcap installed; why did the configure script not find pcap.h or bpf.h?""") answer(""" Are you sure pcap.h and bpf.h are installed? The official distribution of libpcap only installs the libpcap.a library file when "make install" is run. To install pcap.h and bpf.h, you must run "make install-incl". If you're running Debian or Redhat, make sure you have the "libpcap-dev" or "libpcap-devel" packages installed. <br> It's also possible that pcap.h and bpf.h have been installed in a strange location. If this is the case, you may have to tweak aclocal.m4. """) question(""" Why do I get the error <em>dftest_DEPENDENCIES was already defined in condition TRUE, which implies condition HAVE_PLUGINS_TRUE</em> when I try to build Wireshark from SVN or a SVN snapshot? """) answer(""" You probably have automake 1.5 installed on your machine (the command <kbd>automake --version</kbd> will report the version of automake on your machine). There is a bug in that version of automake that causes this problem; upgrade to a later version of automake (1.6 or later). """) question(""" Why does the linker fail with a number of "Output line too long." messages followed by linker errors when I try to build Wireshark? """) answer(""" The version of the <code>sed</code> command on your system is incapable of handling very long lines. On Solaris, for example, <code>/usr/bin/sed</code> has a line length limit too low to allow <code>libtool</code> to work; <code>/usr/xpg4/bin/sed</code> can handle it, as can GNU <code>sed</code> if you have it installed. <br> On Solaris, changing your command search path to search <code>/usr/xpg4/bin</code> before <code>/usr/bin</code> should make the problem go away; on any platform on which you have this problem, installing GNU <code>sed</code> and changing your command path to search the directory in which it is installed before searching the directory with the version of <code>sed</code> that came with the OS should make the problem go away. """) question(""" When I try to build Wireshark on Solaris, why does the link fail complaining that <code>plugin_list</code> is undefined? """) answer(""" This appears to be due to a problem with some versions of the GTK+ and GLib packages from www.sunfreeware.org; un-install those packages, and try getting the 1.2.10 versions from that site, or the versions from <a href="http://www.thewrittenword.com">The Written Word</a>, or the versions from Sun's GNOME distribution, or the versions from the supplemental software CD that comes with the Solaris media kit, or build them from source from <a href="http://www.gtk.org/">the GTK Web site</a>. Then re-run the configuration script, and try rebuilding Wireshark. (If you get the 1.2.10 versions from www.sunfreeware.org, and the problem persists, un-install them and try installing one of the other versions mentioned.) """) question(""" When I try to build Wireshark on Windows, why does the build fail because of conflicts between <code>winsock.h</code> and <code>winsock2.h</code>? """) answer(""" As of Wireshark 0.9.5, you must install WinPcap 2.3 or later, and the corresponding version of the developer's pack, in order to be able to compile Wireshark; it will not compile with older versions of the developer's pack. The symptoms of this failure are conflicts between definitions in <code>winsock.h</code> and in <code>winsock2.h</code>; Wireshark uses <code>winsock2.h</code>, but pre-2.3 versions of the WinPcap developer's packet use <code>winsock.h</code>. (2.3 uses <code>winsock2.h</code>, so if Wireshark were to use <code>winsock.h</code>, it would not be able to build with current versions of the WinPcap developer's pack.) <br> Note that the installed version of the developer's pack should be the same version as the version of WinPcap you have installed. """) ################################################################# section("Starting Wireshark") ################################################################# question("""Why does Wireshark crash with a Bus Error when I try to run it on Solaris 8?""") answer(""" Some versions of the GTK+ library from www.sunfreeware.org appear to be buggy, causing Wireshark to drop core with a Bus Error. Un-install those packages, and try getting the 1.2.10 version from that site, or the version from <a href="http://www.thewrittenword.com">The Written Word</a>, or the version from Sun's GNOME distribution, or the version from the supplemental software CD that comes with the Solaris media kit, or build it from source from <a href="http://www.gtk.org/">the GTK Web site</a>. Update the GLib library to the 1.2.10 version, from the same source, as well. (If you get the 1.2.10 versions from www.sunfreeware.org, and the problem persists, un-install them and try installing one of the other versions mentioned.) <br> Similar problems may exist with older versions of GTK+ for earlier versions of Solaris. """) question("""When I try to run Wireshark, why does it complain about <code>sprint_realloc_objid</code> being undefined?""") answer(""" Wireshark can only be linked with version 4.2.2 or later of UCD SNMP. Your version of Wireshark was dynamically linked with such a version of UCD SNMP; however, you have an older version of UCD SNMP installed, which means that when Wireshark is run, it tries to link to the older version, and fails. You will have to replace that version of UCD SNMP with version 4.2.2 or a later version. """) question(""" I've installed Wireshark from Fink on OS X; why is it very slow to start up? """) answer(""" When an application is installed on OS X, prior to 10.4, it is usually "prebound" to speed up launching the application. (That's what the "Optimizing" phase of installation is.) <br> Fink normally performs prebinding automatically when you install a package. However, in some rare cases, for whatever reason the prebinding caches get corrupt, and then not only does prebinding fail, but startup actually becomes much slower, because the system tries in vain to perform prebinding "on the fly" as you launch the application. This fails, causing sometimes huge delays. <br> To fix the prebinding caches, run the command </p> <pre> sudo /sw/var/lib/fink/prebound/update-package-prebinding.pl -f </pre> <p> """) ################################################################# section("Crashes and other fatal errors") ################################################################# question(""" I have an XXX network card on my machine; if I try to capture on it, why does my machine crash or reset itself? """) answer(""" This is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the libpcap/WinPcap library and, if this is Windows, the WinPcap device driver; </ul> <p> so: </p> <ul> <li>if you are using Windows, see <a href="https://www.winpcap.org/contact.htm">the WinPcap support page</a> - check the "Submitting bugs" section; <li>if you are using some Linux distribution, some version of BSD, or some other UNIX-flavored OS, you should report the problem to the company or organization that produces the OS (in the case of a Linux distribution, report the problem to whoever produces the distribution). </ul> <p> """) question(""" Why does my machine crash or reset itself when I select "Start" from the "Capture" menu or select "Preferences" from the "Edit" menu? """) answer(""" Both of those operations cause Wireshark to try to build a list of the interfaces that it can open; it does so by getting a list of interfaces and trying to open them. There is probably an OS, driver, or, for Windows, WinPcap bug that causes the system to crash when this happens; see the previous question. """) ################################################################# section("Capturing packets") ################################################################# question("""When I use Wireshark to capture packets, why do I see only packets to and from my machine, or not see all the traffic I'm expecting to see from or to the machine I'm trying to monitor?""", "promiscsniff") answer(""" This might be because the interface on which you're capturing is plugged into an Ethernet or Token Ring switch; on a switched network, unicast traffic between two ports will not necessarily appear on other ports - only broadcast and multicast traffic will be sent to all ports. <br> Note that even if your machine is plugged into a hub, the "hub" may be a switched hub, in which case you're still on a switched network. <br> Note also that on the Linksys Web site, they say that their auto-sensing hubs "broadcast the 10Mb packets to the port that operate at 10Mb only and broadcast the 100Mb packets to the ports that operate at 100Mb only", which would indicate that if you sniff on a 10Mb port, you will not see traffic coming sent to a 100Mb port, and <i>vice versa</i>. This problem has also been reported for Netgear dual-speed hubs, and may exist for other "auto-sensing" or "dual-speed" hubs. <br> Some switches have the ability to replicate all traffic on all ports to a single port so that you can plug your analyzer into that single port to sniff all traffic. You would have to check the documentation for the switch to see if this is possible and, if so, to see how to do this. See <a href="https://wiki.wireshark.org/SwitchReference">the switch reference page</a> on <a href="https://wiki.wireshark.org/">the Wireshark Wiki</a> for information on some switches. (Note that it's a Wiki, so you can update or fix that information, or add additional information on those switches or information on new switches, yourself.) <br> Note also that many firewall/NAT boxes have a switch built into them; this includes many of the "cable/DSL router" boxes. If you have a box of that sort, that has a switch with some number of Ethernet ports into which you plug machines on your network, and another Ethernet port used to connect to a cable or DSL modem, you can, at least, sniff traffic between the machines on your network and the Internet by plugging the Ethernet port on the router going to the modem, the Ethernet port on the modem, and the machine on which you're running Wireshark into a hub (make sure it's not a switching hub, and that, if it's a dual-speed hub, all three of those ports are running at the same speed. <br> If your machine is <em>not</em> plugged into a switched network or a dual-speed hub, or it is plugged into a switched network but the port is set up to have all traffic replicated to it, the problem might be that the network interface on which you're capturing doesn't support "promiscuous" mode, or because your OS can't put the interface into promiscuous mode. Normally, network interfaces supply to the host only: </p> <ul> <li>packets sent to one of that host's link-layer addresses; <li>broadcast packets; <li>multicast packets sent to a multicast address that the host has configured the interface to accept. </ul> <p> Most network interfaces can also be put in "promiscuous" mode, in which they supply to the host all network packets they see. Wireshark will try to put the interface on which it's capturing into promiscuous mode unless the "Capture packets in promiscuous mode" option is turned off in the "Capture Options" dialog box, and TShark will try to put the interface on which it's capturing into promiscuous mode unless the <code>-p</code> option was specified. However, some network interfaces don't support promiscuous mode, and some OSes might not allow interfaces to be put into promiscuous mode. <br> If the interface is not running in promiscuous mode, it won't see any traffic that isn't intended to be seen by your machine. It <strong>will</strong> see broadcast packets, and multicast packets sent to a multicast MAC address the interface is set up to receive. <br> You should ask the vendor of your network interface whether it supports promiscuous mode. If it does, you should ask whoever supplied the driver for the interface (the vendor, or the supplier of the OS you're running on your machine) whether it supports promiscuous mode with that network interface. <br> In the case of token ring interfaces, the drivers for some of them, on Windows, may require you to enable promiscuous mode in order to capture in promiscuous mode. See <a href="https://wiki.wireshark.org/CaptureSetup/TokenRing">the Wireshark Wiki item on Token Ring capturing</a> for details. <br> In the case of wireless LAN interfaces, it appears that, when those interfaces are promiscuously sniffing, they're running in a significantly different mode from the mode that they run in when they're just acting as network interfaces (to the extent that it would be a significant effort for those drivers to support for promiscuously sniffing <em>and</em> acting as regular network interfaces at the same time), so it may be that Windows drivers for those interfaces don't support promiscuous mode. """) question("""When I capture with Wireshark, why can't I see any TCP packets other than packets to and from my machine, even though another analyzer on the network sees those packets?""") answer(""" You're probably not seeing <em>any</em> packets other than unicast packets to or from your machine, and broadcast and multicast packets; a switch will normally send to a port only unicast traffic sent to the MAC address for the interface on that port, and broadcast and multicast traffic - it won't send to that port unicast traffic sent to a MAC address for some other interface - and a network interface not in promiscuous mode will receive only unicast traffic sent to the MAC address for that interface, broadcast traffic, and multicast traffic sent to a multicast MAC address the interface is set up to receive. <br> TCP doesn't use broadcast or multicast, so you will only see your own TCP traffic, but UDP services may use broadcast or multicast so you'll see some UDP traffic - however, this is not a problem with TCP traffic, it's a problem with unicast traffic, as you also won't see all UDP traffic between other machines. <br> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question("""Why am I only seeing ARP packets when I try to capture traffic?""") answer(""" You're probably on a switched network, and running Wireshark on a machine that's not sending traffic to the switch and not being sent any traffic from other machines on the switch. ARP packets are often broadcast packets, which are sent to all switch ports. <br> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question(""" Why am I not seeing any traffic when I try to capture traffic?""") answer(""" Is the machine running Wireshark sending out any traffic on the network interface on which you're capturing, or receiving any traffic on that network, or is there any broadcast traffic on the network or multicast traffic to a multicast group to which the machine running Wireshark belongs? <br> If not, this may just be a problem with promiscuous sniffing, either due to running on a switched network or a dual-speed hub, or due to problems with the interface not supporting promiscuous mode; see the response to <a href="#promiscsniff">this earlier question</a>. <br> Otherwise, on Windows, see the response to <a href="#capprobwin">this question</a> and, on a UNIX-flavored OS, see the response to <a href="#capprobunix">this question</a>. """) question(""" Can Wireshark capture on (my T1/E1 line, SS7 links, etc.)? """) answer(""" Wireshark can only capture on devices supported by libpcap/WinPcap. On most OSes, only devices that can act as network interfaces of the type that support IP are supported as capture devices for libpcap/WinPcap, although the device doesn't necessarily have to be running as an IP interface in order to support traffic capture. <br> On Linux and FreeBSD, libpcap 0.8 and later support the API for <a href="http://www.endace.com/products.htm">Endace Measurement Systems' DAG cards</a>, so that a system with one of those cards, and its driver and libraries, installed can capture traffic with those cards with libpcap-based applications. You would either have to have a version of Wireshark built with that version of libpcap, or a dynamically-linked version of Wireshark and a shared libpcap library with DAG support, in order to do so with Wireshark. You should ask Endace whether that could be used to capture traffic on, for example, your T1/E1 link. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/SS7">the SS7 capture setup page</a> on <a href="https://wiki.wireshark.org/">the Wireshark Wiki</a> for current information on capturing SS7 traffic on TDM links. """) question("""How do I put an interface into promiscuous mode?""") answer(""" By not disabling promiscuous mode when running Wireshark or TShark. <br> Note, however, that: </p> <ul> <li>the form of promiscuous mode that libpcap (the library that programs such as tcpdump, Wireshark, etc. use to do packet capture) turns on will <strong>not</strong> necessarily be shown if you run <code>ifconfig</code> on the interface on a UNIX system; <li>some network interfaces might not support promiscuous mode, and some drivers might not allow promiscuous mode to be turned on - see <a href="#promiscsniff">this earlier question</a> for more information on that; <li>the fact that you're not seeing any traffic, or are only seeing broadcast traffic, or aren't seeing any non-broadcast traffic other than traffic to or from the machine running Wireshark, does not mean that promiscuous mode isn't on - see <a href="#promiscsniff">this earlier question</a> for more information on that. </ul> <p> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question(""" I can set a display filter just fine; why don't capture filters work? """) answer(""" Capture filters currently use a different syntax than display filters. Here's the corresponding section from the <a href="https://www.wireshark.org/docs/man-pages/wireshark.html">wireshark(1)</a> man page: <br> "Display filters in Wireshark are very powerful; more fields are filterable in Wireshark than in other protocol analyzers, and the syntax you can use to create your filters is richer. As Wireshark progresses, expect more and more protocol fields to be allowed in display filters. <br> Packet capturing is performed with the pcap library. The capture filter syntax follows the rules of the pcap library. This syntax is different from the display filter syntax." <br> The capture filter syntax used by libpcap can be found in the <a href="http://www.tcpdump.org/tcpdump_man.html">tcpdump(8)</a> man page. """) question("""I'm entering valid capture filters; why do I still get "parse error" errors?""") answer(""" There is a bug in some versions of libpcap/WinPcap that cause it to report parse errors even for valid expressions if a previous filter expression was invalid and got a parse error. <br> Try exiting and restarting Wireshark; if you are using a version of libpcap/WinPcap with this bug, this will "erase" its memory of the previous parse error. If the capture filter that got the "parse error" now works, the earlier error with that filter was probably due to this bug. <br> The bug was fixed in libpcap 0.6; 0.4[.x] and 0.5[.x] versions of libpcap have this bug, but 0.6[.x] and later versions don't. <br> Versions of WinPcap prior to 2.3 are based on pre-0.6 versions of libpcap, and have this bug; WinPcap 2.3 is based on libpcap 0.6.2, and doesn't have this bug. <br> If you are running Wireshark on a UNIX-flavored platform, run "wireshark -v", or select "About Wireshark..." from the "Help" menu in Wireshark, to see what version of libpcap it's using. If it's not 0.6 or later, you will need either to upgrade your OS to get a later version of libpcap, or will need to build and install a later version of libpcap from <a href="http://www.tcpdump.org/">the tcpdump.org Web site</a> and then recompile Wireshark from source with that later version of libpcap. <br> If you are running Wireshark on Windows with a pre-2.3 version of WinPcap, you will need to un-install WinPcap and then download and install WinPcap 2.3. """) question(""" How can I capture packets with CRC errors? """) answer(""" Wireshark can capture only the packets that the packet capture library - libpcap on UNIX-flavored OSes, and the WinPcap port to Windows of libpcap on Windows - can capture, and libpcap/WinPcap can capture only the packets that the OS's raw packet capture mechanism (or the WinPcap driver, and the underlying OS networking code and network interface drivers, on Windows) will allow it to capture. <br> Unless the OS always supplies packets with errors such as invalid CRCs to the raw packet capture mechanism, or can be configured to do so, invalid CRCs to the raw packet capture mechanism, Wireshark - and other programs that capture raw packets, such as tcpdump - cannot capture those packets. You will have to determine whether your OS needs to be so configured and, if so, can be so configured, configure it if necessary and possible, and make whatever changes to libpcap and the packet capture program you're using are necessary, if any, to support capturing those packets. <br> Most OSes probably do <strong>not</strong> support capturing packets with invalid CRCs on Ethernet, and probably do not support it on most other link-layer types. Some drivers on some OSes do support it, such as some Ethernet drivers on FreeBSD; in those OSes, you might always get those packets, or you might only get them if you capture in promiscuous mode (you'd have to determine which is the case). <br> Note that libpcap does not currently supply to programs that use it an indication of whether the packet's CRC was invalid (because the drivers themselves do not supply that information to the raw packet capture mechanism); therefore, Wireshark will not indicate which packets had CRC errors unless the FCS was captured (see the next question) and you're using Wireshark 0.9.15 and later, in which case Wireshark will check the CRC and indicate whether it's correct or not. """) question(""" How can I capture entire frames, including the FCS? """) answer(""" Wireshark can only capture data that the packet capture library - libpcap on UNIX-flavored OSes, and the WinPcap port to Windows of libpcap on Windows - can capture, and libpcap/WinPcap can capture only the data that the OS's raw packet capture mechanism (or the WinPcap driver, and the underlying OS networking code and network interface drivers, on Windows) will allow it to capture. <br> For any particular link-layer network type, unless the OS supplies the FCS of a frame as part of the frame, or can be configured to do so, Wireshark - and other programs that capture raw packets, such as tcpdump - cannot capture the FCS of a frame. You will have to determine whether your OS needs to be so configured and, if so, can be so configured, configure it if necessary and possible, and make whatever changes to libpcap and the packet capture program you're using are necessary, if any, to support capturing the FCS of a frame. <br> Most OSes do <strong>not</strong> support capturing the FCS of a frame on Ethernet, and probably do not support it on most other link-layer types. Some drivres on some OSes do support it, such as some (all?) Ethernet drivers on NetBSD and possibly the driver for Apple's gigabit Ethernet interface in OS X; in those OSes, you might always get the FCS, or you might only get the FCS if you capture in promiscuous mode (you'd have to determine which is the case). <br> Versions of Wireshark prior to 0.9.15 will not treat an Ethernet FCS in a captured packet as an FCS. 0.9.15 and later will attempt to determine whether there's an FCS at the end of the frame and, if it thinks there is, will display it as such, and will check whether it's the correct CRC-32 value or not. """) question(""" I'm capturing packets on a machine on a VLAN; why don't the packets I'm capturing have VLAN tags? """) answer(""" You might be capturing on what might be called a "VLAN interface" - the way a particular OS makes VLANs plug into the networking stack might, for example, be to have a network device object for the physical interface, which takes VLAN packets, strips off the VLAN header and constructs an Ethernet header, and passes that packet to an internal network device object for the VLAN, which then passes the packets onto various higher-level protocol implementations. <br> In order to see the raw Ethernet packets, rather than "de-VLANized" packets, you would have to capture not on the virtual interface for the VLAN, but on the interface corresponding to the physical network device, if possible. See <a href="https://wiki.wireshark.org/CaptureSetup/VLAN">the Wireshark Wiki item on VLAN capturing</a> for details. """) question(""" Why does Wireshark hang after I stop a capture? """) answer(""" The most likely reason for this is that Wireshark is trying to look up an IP address in the capture to convert it to a name (so that, for example, it can display the name in the source address or destination address columns), and that lookup process is taking a very long time. <br> Wireshark calls a routine in the OS of the machine on which it's running to convert of IP addresses to the corresponding names. That routine probably does one or more of: </p> <ul><li>a search of a system file listing IP addresses and names; <li>a lookup using DNS; <li>on UNIX systems, a lookup using NIS; <li>on Windows systems, a NetBIOS-over-TCP query. </ul> <p> If a DNS server that's used in an address lookup is not responding, the lookup will fail, but will only fail after a timeout while the system routine waits for a reply. <br> In addition, on Windows systems, if the DNS lookup of the address fails, either because the server isn't responding or because there are no records in the DNS that could be used to map the address to a name, a NetBIOS-over-TCP query will be made. That query involves sending a message to the NetBIOS-over-TCP name service on that machine, asking for the name and other information about the machine. If the machine isn't running software that responds to those queries - for example, many non-Windows machines wouldn't be running that software - the lookup will only fail after a timeout. Those timeouts can cause the lookup to take a long time. <br> If you disable network address-to-name translation - for example, by turning off the "Enable network name resolution" option in the "Capture Options" dialog box for starting a network capture - the lookups of the address won't be done, which may speed up the process of reading the capture file after the capture is stopped. You can make that setting the default by selecting "Preferences" from the "Edit" menu, turning off the "Enable network name resolution" option in the "Name resolution" options in the preferences disalog box, and using the "Save" button in that dialog box; note that this will save <em>all</em> your current preference settings. <br> If Wireshark hangs when reading a capture even with network name resolution turned off, there might, for example, be a bug in one of Wireshark's dissectors for a protocol causing it to loop infinitely. If you're not running the most recent release of Wireshark, you should first upgrade to that release, as, if there's a bug of that sort, it might've been fixed in a release after the one you're running. If the hang occurs in the most recent release of Wireshark, the bug should be reported to <a href="mailto:wireshark-dev@wireshark.org">the Wireshark developers' mailing list</a> at <code>wireshark-dev@wireshark.org</code>. <br> On UNIX-flavored OSes, please try to force Wireshark to dump core, by sending it a <code>SIGABRT</code> signal (usually signal 6) with the <code>kill</code> command, and then get a stack trace if you have a debugger installed. A stack trace can be obtained by using your debugger (<code>gdb</code> in this example), the Wireshark binary, and the resulting core file. Here's an example of how to use the gdb command <code>backtrace</code> to do so. </p> <pre> $ gdb wireshark core (gdb) backtrace ..... prints the stack trace (gdb) quit $ </pre> <p> The core dump file may be named "wireshark.core" rather than "core" on some platforms (e.g., BSD systems). <br> Also, if at all possible, please send a copy of the capture file that caused the problem. When capturing packets, Wireshark normally writes captured packets to a temporary file, which will probably be in <code>/tmp</code> or <code>/var/tmp</code> on UNIX-flavored OSes, <code>\\TEMP</code> on the main system disk (normally <code>\\Documents and Settings\\</code><var>your login name</var> <code>\\Local Settings\\Temp</code> on the main system disk on Windows Windows XP and Server 2003, and <code>\\Users\\<var>your login name</var>\\AppData\\Local\\Temp</code> on the main system disk on Windows Vista and later, so the capture file will probably be there. If you are capturing on a single interface, it will have a name of the form, <code>wireshark_&lt;fmt&gt;_&lt;iface&gt;_YYYYmmddHHMMSS_XXXXXX</code>, where &lt;fmt&gt; is the capture file format (pcap or pcapng), and &lt;iface&gt; is the actual name of the interface you are capturing on; otherwise, if you are capturing on multiple interfaces, it will have a name of the form, <code>wireshark_&lt;N&gt;_interfaces_YYYYmmddHHMMSS_XXXXXX</code>, where &lt;N&gt; is the number of simultaneous interfaces you are capturing on. Please don't send a trace file greater than 1 MB when compressed; instead, make it available via FTP or HTTP, or say it's available but leave it up to a developer to ask for it. If the trace file contains sensitive information (e.g., passwords), then please do not send it. """) ################################################################# section("Capturing packets on Windows") ################################################################# question(""" I'm running Wireshark on Windows; why does some network interface on my machine not show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start", and/or why does Wireshark give me an error if I try to capture on that interface? """, "capprobwin") answer(""" If you are running Wireshark on Windows XP, or Windows Server 2003, and this is the first time you have run a WinPcap-based program (such as Wireshark, or TShark, or WinDump, or Analyzer, or...) since the machine was rebooted, you need to run that program from an account with administrator privileges; once you have run such a program, you will not need administrator privileges to run any such programs until you reboot. <br> If you are running on Windows Windows XP or Windows Server 2003 and have administrator privileges or a WinPcap-based program has been run with those privileges since the machine rebooted, this problem <em>might</em> clear up if you completely un-install WinPcap and then re-install it. <br> If that doesn't work, then note that Wireshark relies on the WinPcap library, on the WinPcap device driver, and on the facilities that come with the OS on which it's running in order to do captures. <br> Therefore, if the OS, the WinPcap library, or the WinPcap driver don't support capturing on a particular network interface device, Wireshark won't be able to capture on that device. <br> WinPcap 2.3 has problems supporting PPP WAN interfaces on Windows NT 4.0, Windows 2000, Windows XP, and Windows Server 2003, and, to avoid those problems, support for PPP WAN interfaces on those versions of Windows has been disabled in WinPcap 3.0. Regular dial-up lines, ISDN lines, ADSL connections using PPPoE or PPPoA, and various other lines such as T1/E1 lines are all PPP interfaces, so those interfaces might not show up on the list of interfaces in the "Capture Options" dialog on those OSes. <br> On Windows 2000, Windows XP, and Windows Server 2003, but <strong>not</strong> Windows NT 4.0 or Windows Vista Beta 1, you should be able to capture on the "GenericDialupAdapter" with WinPcap 3.1. (3.1 beta releases called it the "NdisWanAdapter"; if you're using a 3.1 beta release, you should un-install it and install the final 3.1 release.) See <a href="https://wiki.wireshark.org/CaptureSetup/PPP">the Wireshark Wiki item on PPP capturing</a> for details. <br> WinPcap prior to 3.0 does not support multiprocessor machines (note that machines with a single multi-threaded processor, such as Intel's new multi-threaded x86 processors, are multiprocessor machines as far as the OS and WinPcap are concerned), and recent 2.x versions of WinPcap refuse to operate if they detect that they're running on a multiprocessor machine, which means that they may not show any network interfaces. You will need to use WinPcap 3.0 to capture on a multiprocessor machine. <br> If an interface doesn't show up in the list of interfaces in the "Interface:" field, and you know the name of the interface, try entering that name in the "Interface:" field and capturing on that device. <br> If the attempt to capture on it succeeds, the interface is somehow not being reported by the mechanism Wireshark uses to get a list of interfaces. Try listing the interfaces with WinDump; see <a href="https://www.windump.org/">the WinDump Web site</a> for information on using WinDump. <br> You would run WinDump with the <code>-D</code> flag; if it lists the interface, please report this to <a href="mailto:wireshark-dev@wireshark.org">wireshark-dev@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system; <li>the type of network device you're using; <li>the output of WinDump. </ul> <p> If WinDump does <em>not</em> list the interface, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the WinPcap library and/or the WinPcap device driver; </ul> <p> so first check <a href="https://www.winpcap.org/misc/faq.htm">the WinPcap FAQ</a> to see if your problem is mentioned there. If not, then see <a href="https://www.winpcap.org/contact.htm">the WinPcap support page</a> - check the "Submitting bugs" section. <br> If you are having trouble capturing on a particular network interface, first try capturing on that device with WinDump; see <a href="https://www.windump.org/">the WinDump Web site</a> for information on using WinDump. <br> If you can capture on the interface with WinDump, send mail to <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system; <li>the type of network device you're using; <li>the error message you get from Wireshark. </ul> <p> If you <em>cannot</em> capture on the interface with WinDump, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the WinPcap library and/or the WinPcap device driver; </ul> <p> so first check <a href="https://www.winpcap.org/misc/faq.htm">the WinPcap FAQ</a> to see if your problem is mentioned there. If not, then see <a href="https://www.winpcap.org/contact.htm">the WinPcap support page</a> - check the "Submitting bugs" section. <br> You may also want to ask the <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> and the <a href="mailto:winpcap-users@winpcap.org">winpcap-users@winpcap.org</a> mailing lists to see if anybody happens to know about the problem and know a workaround or fix for the problem. (Note that you will have to subscribe to that list in order to be allowed to mail to it; see <a href="https://www.winpcap.org/contact.htm">the WinPcap support page</a> for information on the mailing list.) In your mail, please give full details of the problem, as described above, and also indicate that the problem occurs with WinDump, not just with Wireshark. """) question(""" I'm running Wireshark on Windows; why do no network interfaces show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" This is really <a href="#capprobwin">the same question as a previous one</a>; see the response to that question. """) question(""" I'm running Wireshark on Windows; why doesn't my serial port/ADSL modem/ISDN modem show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" Internet access on those devices is often done with the Point-to-Point (PPP) protocol; WinPcap 2.3 has problems supporting PPP WAN interfaces on Windows NT 4.0, Windows 2000, Windows XP, and Windows Server 2003, and, to avoid those problems, support for PPP WAN interfaces on those versions of Windows has been disabled in WinPcap 3.0. <br> On Windows 2000, Windows XP, and Windows Server 2003, but <strong>not</strong> Windows NT 4.0 or Windows Vista Beta 1, you should be able to capture on the "GenericDialupAdapter" with WinPcap 3.1. (3.1 beta releases called it the "NdisWanAdapter"; if you're using a 3.1 beta release, you should un-install it and install the final 3.1 release.) See <a href="https://wiki.wireshark.org/CaptureSetup/PPP">the Wireshark Wiki item on PPP capturing</a> for details. """) question(""" I'm running Wireshark on Windows NT 4.0/Windows 2000/Windows XP/Windows Server 2003; my machine has a PPP (dial-up POTS, ISDN, etc.) interface, and it shows up in the "Interface" item in the "Capture Options" dialog box. Why can no packets be sent on or received from that network while I'm trying to capture traffic on that interface?""", "nt_ppp_sniff") answer(""" Some versions of WinPcap have problems with PPP WAN interfaces on Windows NT 4.0, Windows 2000, Windows XP, and Windows Server 2003; one symptom that may be seen is that attempts to capture in promiscuous mode on the interface cause the interface to be incapable of sending or receiving packets. You can disable promiscuous mode using the <code>-p</code> command-line flag or the item in the "Capture Preferences" dialog box, but this may mean that outgoing packets, or incoming packets, won't be seen in the capture. <br> On Windows 2000, Windows XP, and Windows Server 2003, but <strong>not</strong> Windows NT 4.0 or Windows Vista Beta 1, you should be able to capture on the "GenericDialupAdapter" with WinPcap 3.1. (3.1 beta releases called it the "NdisWanAdapter"; if you're using a 3.1 beta release, you should un-install it and install the final 3.1 release.) See <a href="https://wiki.wireshark.org/CaptureSetup/PPP">the Wireshark Wiki item on PPP capturing</a> for details. """) question(""" I'm running Wireshark on Windows; why am I not seeing any traffic being sent by the machine running Wireshark?""") answer(""" If you are running some form of VPN client software, it might be causing this problem; people have seen this problem when they have Check Point's VPN software installed on their machine. If that's the cause of the problem, you will have to remove the VPN software in order to have Wireshark (or any other application using WinPcap) see outgoing packets; unfortunately, neither we nor the WinPcap developers know any way to make WinPcap and the VPN software work well together. <br> Also, some drivers for Windows (especially some wireless network interface drivers) apparently do not, when running in promiscuous mode, arrange that outgoing packets are delivered to the software that requested that the interface run promiscuously; try turning promiscuous mode off. """) question(""" When I capture on Windows in promiscuous mode, I can see packets other than those sent to or from my machine; however, those packets show up with a "Short Frame" indication, unlike packets to or from my machine. What should I do to arrange that I see those packets in their entirety? """) answer(""" In at least some cases, this appears to be the result of PGPnet running on the network interface on which you're capturing; turn it off on that interface. """) question(""" I'm trying to capture 802.11 traffic on Windows; why am I not seeing any packets? """, "win802_11promisc") answer(""" At least some 802.11 card drivers on Windows appear not to see any packets if they're running in promiscuous mode. Try turning promiscuous mode off; you'll only be able to see packets sent by and received by your machine, not third-party traffic, and it'll look like Ethernet traffic and won't include any management or control frames, but that's a limitation of the card drivers. <br> See the archived <a href="https://web.archive.org/web/20090226193157/http://www.micro-logix.com/winpcap/Supported.asp">MicroLogix's list of cards supported with WinPcap</a> for information on support of various adapters and drivers with WinPcap. """) question(""" I'm trying to capture 802.11 traffic on Windows; why am I seeing packets received by the machine on which I'm capturing traffic, but not packets sent by that machine? """) answer(""" This appears to be another problem with promiscuous mode; try turning it off. """) question(""" I'm trying to capture Ethernet VLAN traffic on Windows, and I'm capturing on a "raw" Ethernet device rather than a "VLAN interface", so that I can see the VLAN headers; why am I seeing packets received by the machine on which I'm capturing traffic, but not packets sent by that machine? """) answer(""" The way the Windows networking code works probably means that packets are sent on a "VLAN interface" rather than the "raw" device, so packets sent by the machine will only be seen when you capture on the "VLAN interface". If so, you will be unable to see outgoing packets when capturing on the "raw" device, so you are stuck with a choice between seeing VLAN headers and seeing outgoing packets. """) ################################################################# section("Capturing packets on UN*Xes") ################################################################# question(""" I'm running Wireshark on a UNIX-flavored OS; why does some network interface on my machine not show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start", and/or why does Wireshark give me an error if I try to capture on that interface? """, "capprobunix") answer(""" You may need to run Wireshark from an account with sufficient privileges to capture packets, such as the super-user account, or may need to give your account sufficient privileges to capture packets. Only those interfaces that Wireshark can open for capturing show up in that list; if you don't have sufficient privileges to capture on any interfaces, no interfaces will show up in the list. See <a href="https://wiki.wireshark.org/CaptureSetup/CapturePrivileges">the Wireshark Wiki item on capture privileges</a> for details on how to give a particular account or account group capture privileges on platforms where that can be done. <br> If you are running Wireshark from an account with sufficient privileges, then note that Wireshark relies on the libpcap library, and on the facilities that come with the OS on which it's running in order to do captures. On some OSes, those facilities aren't present by default; see <a href="https://wiki.wireshark.org/CaptureSetup/CaptureSupport">the Wireshark Wiki item on adding capture support</a> for details. <br> And, even if you're running with an account that has sufficient privileges to capture, and capture support is present in your OS, if the OS or the libpcap library don't support capturing on a particular network interface device or particular types of devices, Wireshark won't be able to capture on that device. <br> On Solaris, note that libpcap 0.6.2 and earlier didn't support Token Ring interfaces; the current version, 0.7.2, does support Token Ring, and the current version of Wireshark works with libpcap 0.7.2 and later. <br> If an interface doesn't show up in the list of interfaces in the "Interface:" field, and you know the name of the interface, try entering that name in the "Interface:" field and capturing on that device. <br> If the attempt to capture on it succeeds, the interface is somehow not being reported by the mechanism Wireshark uses to get a list of interfaces; please report this to <a href="mailto:wireshark-dev@wireshark.org">wireshark-dev@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system (for Linux, give both the version number of the kernel and the name and version number of the distribution you're using); <li>the type of network device you're using. </ul> <p> If you are having trouble capturing on a particular network interface, and you've made sure that (on platforms that require it) you've arranged that packet capture support is present, as per the above, first try capturing on that device with <code>tcpdump</code>. <br> If you can capture on the interface with <code>tcpdump</code>, send mail to <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system (for Linux, give both the version number of the kernel and the name and version number of the distribution you're using); <li>the type of network device you're using; <li>the error message you get from Wireshark. </ul> <p> If you <em>cannot</em> capture on the interface with <code>tcpdump</code>, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the libpcap library; </ul> <p> so you should report the problem to the company or organization that produces the OS (in the case of a Linux distribution, report the problem to whoever produces the distribution). <br> You may also want to ask the <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> and the <a href="mailto:tcpdump-workers@lists.tcpdump.org">tcpdump-workers@lists.tcpdump.org</a> mailing lists to see if anybody happens to know about the problem and know a workaround or fix for the problem. In your mail, please give full details of the problem, as described above, and also indicate that the problem occurs with <code>tcpdump</code> not just with Wireshark. """) question(""" I'm running Wireshark on a UNIX-flavored OS; why do no network interfaces show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" This is really <a href="#capprobunix">the same question as the previous one</a>; see the response to that question. """) question("""I'm capturing packets on Linux; why do the time stamps have only 100ms resolution, rather than 1us resolution?""") answer(""" Wireshark gets time stamps from libpcap/WinPcap, and libpcap/WinPcap get them from the OS kernel, so Wireshark - and any other program using libpcap, such as tcpdump - is at the mercy of the time stamping code in the OS for time stamps. <br> At least on x86-based machines, Linux can get high-resolution time stamps on newer processors with the Time Stamp Counter (TSC) register; for example, Intel x86 processors, starting with the Pentium Pro, and including all x86 processors since then, have had a TSC, and other vendors probably added the TSC at some point to their families of x86 processors. The Linux kernel must be configured with the CONFIG_X86_TSC option enabled in order to use the TSC. Make sure this option is enabled in your kernel. <br> In addition, some Linux distributions may have bugs in their versions of the kernel that cause packets not to be given high-resolution time stamps even if the TSC is enabled. See, for example, bug 61111 for Red Hat Linux 7.2. If your distribution has a bug such as this, you may have to run a standard kernel from kernel.org in order to get high-resolution time stamps. """) ################################################################# section("Capturing packets on wireless LANs") ################################################################# question(""" How can I capture raw 802.11 frames, including non-data (management, beacon) frames? """, "raw_80211_sniff") answer(""" That depends on the operating system on which you're running, and on the 802.11 interface on which you're capturing. <br> This would probably require that you capture in promiscuous mode or in the mode called "monitor mode" or "RFMON mode". On some platforms, or with some cards, this might require that you capture in monitor mode - promiscuous mode might not be sufficient. If you want to capture traffic on networks other than the one with which you're associated, you will have to capture in monitor mode. <br> Not all operating systems support capturing non-data packets and, even on operating systems that do support it, not all drivers, and thus not all interfaces, support it. Even on those that do, monitor mode might not be supported by the operating system or by the drivers for all interfaces. <br> <strong>NOTE:</strong> an interface running in monitor mode will, on most if not all platforms, not be able to act as a regular network interface; putting it into monitor mode will, in effect, take your machine off of whatever network it's on as long as the interface is in monitor mode, allowing it only to passively capture packets. <br> This means that you should disable name resolution when capturing in monitor mode; otherwise, when Wireshark (or TShark, or tcpdump) tries to display IP addresses as host names, it will probably block for a long time trying to resolve the name because it will not be able to communicate with any DNS or NIS servers. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/WLAN">the Wireshark Wiki item on 802.11 capturing</a> for details. """) question(""" How do I capture on an 802.11 device in monitor mode?""", "monitor") answer(""" Whether you will be able to capture in monitor mode depends on the operating system, adapter, and driver you're using. See <a href="#raw_80211_sniff">the previous question</a> for information on monitor mode, including a link to the Wireshark Wiki page that gives details on 802.11 capturing. """) ################################################################# section("Viewing traffic") ################################################################# question("Why am I seeing lots of packets with incorrect TCP checksums?") answer(""" If the packets that have incorrect TCP checksums are all being sent by the machine on which Wireshark is running, this is probably because the network interface on which you're capturing does TCP checksum offloading. That means that the TCP checksum is added to the packet by the network interface, not by the OS's TCP/IP stack; when capturing on an interface, packets being sent by the host on which you're capturing are directly handed to the capture interface by the OS, which means that they are handed to the capture interface without a TCP checksum being added to them. <br> The only way to prevent this from happening would be to disable TCP checksum offloading, but </p> <ol> <li>that might not even be possible on some OSes; <li>that could reduce networking performance significantly. </ol> <p> However, you can disable the check that Wireshark does of the TCP checksum, so that it won't report any packets as having TCP checksum errors, and so that it won't refuse to do TCP reassembly due to a packet having an incorrect TCP checksum. That can be set as an Wireshark preference by selecting "Preferences" from the "Edit" menu, opening up the "Protocols" list in the left-hand pane of the "Preferences" dialog box, selecting "TCP", from that list, turning off the "Check the validity of the TCP checksum when possible" option, clicking "Save" if you want to save that setting in your preference file, and clicking "OK". <br> It can also be set on the Wireshark or TShark command line with a <code>-o tcp.check_checksum:false</code> command-line flag, or manually set in your preferences file by adding a <code>tcp.check_checksum:false</code> line. """) question(""" I've just installed Wireshark, and the traffic on my local LAN is boring. Where can I find more interesting captures? """) answer(""" We have a collection of strange and exotic sample capture files at %s""" % (selflink("https://wiki.wireshark.org/SampleCaptures"))) question(""" Why doesn't Wireshark correctly identify RTP packets? It shows them only as UDP.""") answer(""" Wireshark can identify a UDP datagram as containing a packet of a particular protocol running atop UDP only if </p> <ol> <li> The protocol in question has a particular standard port number, and the UDP source or destination port number is that port <li> Packets of that protocol can be identified by looking for a "signature" of some type in the packet - i.e., some data that, if Wireshark finds it in some particular part of a packet, means that the packet is almost certainly a packet of that type. <li> Some <em>other</em> traffic earlier in the capture indicated that, for example, UDP traffic between two particular addresses and ports will be RTP traffic. </ol> <p> RTP doesn't have a standard port number, so 1) doesn't work; it doesn't, as far as I know, have any "signature", so 2) doesn't work. <br> That leaves 3). If there's RTSP traffic that sets up an RTP session, then, at least in some cases, the RTSP dissector will set things up so that subsequent RTP traffic will be identified. Currently, that's the only place we do that; there may be other places. <br> However, there will always be places where Wireshark is simply <b>incapable</b> of deducing that a given UDP flow is RTP; a mechanism would be needed to allow the user to specify that a given conversation should be treated as RTP. As of Wireshark 0.8.16, such a mechanism exists; if you select a UDP or TCP packet, the right mouse button menu will have a "Decode As..." menu item, which will pop up a dialog box letting you specify that the source port, the destination port, or both the source and destination ports of the packet should be dissected as some particular protocol. """) question(""" Why doesn't Wireshark show Yahoo Messenger packets in captures that contain Yahoo Messenger traffic?""") answer(""" Wireshark only recognizes as Yahoo Messenger traffic packets to or from TCP port 3050 that begin with "YPNS", "YHOO", or "YMSG". TCP segments that start with the middle of a Yahoo Messenger packet that takes more than one TCP segment will not be recognized as Yahoo Messenger packets (even if the TCP segment also contains the beginning of another Yahoo Messenger packet). """) ################################################################# section("Filtering traffic") ################################################################# question("""I saved a filter and tried to use its name to filter the display; why do I get an "Unexpected end of filter string" error?""") answer(""" You cannot use the name of a saved display filter as a filter. To filter the display, you can enter a display filter expression - <strong>not</strong> the name of a saved display filter - in the "Filter:" box at the bottom of the display, and type the &lt;Enter&gt; key or press the "Apply" button (that does not require you to have a saved filter), or, if you want to use a saved filter, you can press the "Filter:" button, select the filter in the dialog box that pops up, and press the "OK" button.""") question(""" How can I search for, or filter, packets that have a particular string anywhere in them? """) answer(""" If you want to do this when capturing, you can't. That's a feature that would be hard to implement in capture filters without changes to the capture filter code, which, on many platforms, is in the OS kernel and, on other platforms, is in the libpcap library. <br> After capture, you can search for text by selecting <i>Edit&#8594;Find Packet...</i> and making sure <i>String</i> is selected. Alternately, you can use the "contains" display filter operator or "matches" operator if it's supported on your system. """) question(""" How do I filter a capture to see traffic for virus XXX? """) answer(""" For some viruses/worms there might be a capture filter to recognize the virus traffic. Check the <a href="https://wiki.wireshark.org/CaptureFilters">CaptureFilters</a> page on the <a href="https://wiki.wireshark.org/">Wireshark Wiki</a> to see if anybody's added such a filter. <br> Note that Wireshark was not designed to be an intrusion detection system; you might be able to use it as an IDS, but in most cases software designed to be an IDS, such as <a href="https://www.snort.org/">Snort</a> or <a href="https://www.prelude-siem.org/">Prelude</a>, will probably work better. """) ################################################################# if __name__ == '__main__': sys.exit(main()) #################################################################
utkbansal/kuma
refs/heads/master
vendor/packages/translate/storage/properties.py
24
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2004-2014 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # translate 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. """Classes that hold units of .properties, and similar, files that are used in translating Java, Mozilla, MacOS and other software. The :class:`propfile` class is a monolingual class with :class:`propunit` providing unit level access. The .properties store has become a general key value pair class with :class:`Dialect` providing the ability to change the behaviour of the parsing and handling of the various dialects. Currently we support: - Java .properties - Mozilla .properties - Adobe Flex files - MacOS X .strings files - Skype .lang files The following provides references and descriptions of the various dialects supported: Java Java .properties are supported completely except for the ability to drop pairs that are not translated. The following `.properties file description <http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream)>`_ gives a good references to the .properties specification. Properties file may also hold Java `MessageFormat <http://docs.oracle.com/javase/1.4.2/docs/api/java/text/MessageFormat.html>`_ messages. No special handling is provided in this storage class for MessageFormat, but this may be implemented in future. All delimiter types, comments, line continuations and spaces handling in delimeters are supported. Mozilla Mozilla files use '=' as a delimiter, are UTF-8 encoded and thus don't need \\u escaping. Any \\U values will be converted to correct Unicode characters. Strings Mac OS X strings files are implemented using `these <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPInternational/Articles/StringsFiles.html>`_ `two <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/LoadingResources/Strings/Strings.html>`_ articles as references. Flex Adobe Flex files seem to be normal .properties files but in UTF-8 just like Mozilla files. This `page <http://livedocs.adobe.com/flex/3/html/help.html?content=l10n_3.html>`_ provides the information used to implement the dialect. Skype Skype .lang files seem to be UTF-16 encoded .properties files. A simple summary of what is permissible follows. Comments supported: .. code-block:: properties # a comment ! a comment // a comment (only at the beginning of a line) /* a comment (not across multiple lines) */ Name and Value pairs: .. code-block:: properties # Delimiters key = value key : value key value # Space in key and around value \ key\ = \ value # Note that the b and c are escaped for reST rendering b = a string with escape sequences \\t \\n \\r \\\\ \\" \\' \\ (space) \u0123 c = a string with a continuation line \\ continuation line # Special cases # key with no value key # value no key (extractable in prop2po but not mergeable in po2prop) =value # .strings specific "key" = "value"; """ import re from translate.lang import data from translate.misc import quote from translate.misc.deprecation import deprecated from translate.storage import base labelsuffixes = (".label", ".title") """Label suffixes: entries with this suffix are able to be comibed with accesskeys found in in entries ending with :attr:`.accesskeysuffixes`""" accesskeysuffixes = (".accesskey", ".accessKey", ".akey") """Accesskey Suffixes: entries with this suffix may be combined with labels ending in :attr:`.labelsuffixes` into accelerator notation""" # the rstripeols convert dos <-> unix nicely as well # output will be appropriate for the platform eol = "\n" def _find_delimiter(line, delimiters): """Find the type and position of the delimiter in a property line. Property files can be delimited by "=", ":" or whitespace (space for now). We find the position of each delimiter, then find the one that appears first. :param line: A properties line :type line: str :param delimiters: valid delimiters :type delimiters: list :return: delimiter character and offset within *line* :rtype: Tuple (delimiter char, Offset Integer) """ delimiter_dict = {} for delimiter in delimiters: delimiter_dict[delimiter] = -1 delimiters = delimiter_dict # Find the position of each delimiter type for delimiter, pos in delimiters.iteritems(): prewhitespace = len(line) - len(line.lstrip()) pos = line.find(delimiter, prewhitespace) while pos != -1: if delimiters[delimiter] == -1 and line[pos-1] != u"\\": delimiters[delimiter] = pos break pos = line.find(delimiter, pos + 1) # Find the first delimiter mindelimiter = None minpos = -1 for delimiter, pos in delimiters.iteritems(): if pos == -1 or delimiter == u" ": continue if minpos == -1 or pos < minpos: minpos = pos mindelimiter = delimiter if mindelimiter is None and delimiters.get(u" ", -1) != -1: # Use space delimiter if we found nothing else return (u" ", delimiters[" "]) if (mindelimiter is not None and u" " in delimiters and delimiters[u" "] < delimiters[mindelimiter]): # If space delimiter occurs earlier than ":" or "=" then it is the # delimiter only if there are non-whitespace characters between it and # the other detected delimiter. if len(line[delimiters[u" "]:delimiters[mindelimiter]].strip()) > 0: return (u" ", delimiters[u" "]) return (mindelimiter, minpos) @deprecated("Use Dialect.find_delimiter instead") def find_delimeter(line): """Misspelled function that is kept around in case someone relies on it. .. deprecated:: 1.7.0 Use :func:`find_delimiter` instead """ return _find_delimiter(line, DialectJava.delimiters) def is_line_continuation(line): """Determine whether *line* has a line continuation marker. .properties files can be terminated with a backslash (\\) indicating that the 'value' continues on the next line. Continuation is only valid if there are an odd number of backslashses (an even number would result in a set of N/2 slashes not an escape) :param line: A properties line :type line: str :return: Does *line* end with a line continuation :rtype: Boolean """ pos = -1 count = 0 if len(line) == 0: return False # Count the slashes from the end of the line. Ensure we don't # go into infinite loop. while len(line) >= -pos and line[pos:][0] == "\\": pos -= 1 count += 1 return (count % 2) == 1 # Odd is a line continuation, even is not def is_comment_one_line(line): """Determine whether a *line* is a one-line comment. :param line: A properties line :type line: unicode :return: True if line is a one-line comment :rtype: bool """ stripped = line.strip() line_starters = (u'#', u'!', u'//', ) for starter in line_starters: if stripped.startswith(starter): return True if stripped.startswith(u'/*') and stripped.endswith(u'*/'): return True return False def is_comment_start(line): """Determine whether a *line* starts a new multi-line comment. :param line: A properties line :type line: unicode :return: True if line starts a new multi-line comment :rtype: bool """ stripped = line.strip() return stripped.startswith('/*') and not stripped.endswith('*/') def is_comment_end(line): """Determine whether a *line* ends a new multi-line comment. :param line: A properties line :type line: unicode :return: True if line ends a new multi-line comment :rtype: bool """ stripped = line.strip() return not stripped.startswith('/*') and stripped.endswith('*/') def _key_strip(key): """Cleanup whitespace found around a key :param key: A properties key :type key: str :return: Key without any unneeded whitespace :rtype: str """ newkey = key.rstrip() # If string now ends in \ we put back the whitespace that was escaped if newkey[-1:] == "\\": newkey += key[len(newkey):len(newkey)+1] return newkey.lstrip() dialects = {} default_dialect = "java" def register_dialect(dialect): """Decorator that registers the dialect.""" dialects[dialect.name] = dialect return dialect def get_dialect(dialect=default_dialect): return dialects.get(dialect) class Dialect(object): """Settings for the various behaviours in key=value files.""" name = None default_encoding = 'iso-8859-1' delimiters = None pair_terminator = u"" key_wrap_char = u"" value_wrap_char = u"" drop_comments = [] @classmethod def encode(cls, string, encoding=None): """Encode the string""" # FIXME: dialects are a bad idea, not possible for subclasses # to override key methods if encoding != "utf-8": return quote.javapropertiesencode(string or u"") return string or u"" @classmethod def find_delimiter(cls, line): """Find the delimiter""" return _find_delimiter(line, cls.delimiters) @classmethod def key_strip(cls, key): """Strip unneeded characters from the key""" return _key_strip(key) @classmethod def value_strip(cls, value): """Strip unneeded characters from the value""" return value.lstrip() @register_dialect class DialectJava(Dialect): name = "java" default_encoding = "iso-8859-1" delimiters = [u"=", u":", u" "] @register_dialect class DialectJavaUtf8(DialectJava): name = "java-utf8" default_encoding = "utf-8" delimiters = [u"=", u":", u" "] @classmethod def encode(cls, string, encoding=None): return quote.mozillapropertiesencode(string or u"") @register_dialect class DialectFlex(DialectJava): name = "flex" default_encoding = "utf-8" @register_dialect class DialectMozilla(DialectJavaUtf8): name = "mozilla" delimiters = [u"="] @classmethod def encode(cls, string, encoding=None): """Encode the string""" string = quote.mozillapropertiesencode(string or u"") string = quote.mozillaescapemarginspaces(string or u"") return string @register_dialect class DialectGaia(DialectMozilla): name = "gaia" delimiters = [u"="] @register_dialect class DialectSkype(Dialect): name = "skype" default_encoding = "utf-16" delimiters = [u"="] @classmethod def encode(cls, string, encoding=None): return quote.mozillapropertiesencode(string or u"") @register_dialect class DialectStrings(Dialect): name = "strings" default_encoding = "utf-16" delimiters = [u"="] pair_terminator = u";" key_wrap_char = u'"' value_wrap_char = u'"' out_ending = u';' out_delimiter_wrappers = u' ' drop_comments = ["/* No comment provided by engineer. */"] @classmethod def key_strip(cls, key): """Strip unneeded characters from the key""" newkey = key.rstrip().rstrip('"') # If string now ends in \ we put back the char that was escaped if newkey[-1:] == "\\": newkey += key[len(newkey):len(newkey)+1] ret = newkey.lstrip().lstrip('"') return ret.replace('\\"', '"') @classmethod def value_strip(cls, value): """Strip unneeded characters from the value""" newvalue = value.rstrip().rstrip(';').rstrip('"') # If string now ends in \ we put back the char that was escaped if newvalue[-1:] == "\\": newvalue += value[len(newvalue):len(newvalue)+1] ret = newvalue.lstrip().lstrip('"') return ret.replace('\\"', '"') @classmethod def encode(cls, string, encoding=None): return string.replace("\n", r"\n").replace("\t", r"\t") @register_dialect class DialectStringsUtf8(DialectStrings): name = "strings-utf8" default_encoding = "utf-8" class propunit(base.TranslationUnit): """An element of a properties file i.e. a name and value, and any comments associated.""" def __init__(self, source="", personality="java"): """Construct a blank propunit.""" self.personality = get_dialect(personality) super(propunit, self).__init__(source) self.name = u"" self.value = u"" self.translation = u"" self.delimiter = u"=" self.comments = [] self.source = source # a pair of symbols to enclose delimiter on the output # (a " " can be used for the sake of convenience) self.out_delimiter_wrappers = getattr(self.personality, 'out_delimiter_wrappers', u'') # symbol that should end every property sentence # (e.g. ";" is required for Mac OS X strings) self.out_ending = getattr(self.personality, 'out_ending', u'') def getsource(self): value = quote.propertiesdecode(self.value) return value def setsource(self, source): self._rich_source = None source = data.forceunicode(source) self.value = self.personality.encode(source or u"", self.encoding) source = property(getsource, setsource) def gettarget(self): translation = quote.propertiesdecode(self.translation) translation = re.sub(u"\\\\ ", u" ", translation) return translation def settarget(self, target): self._rich_target = None target = data.forceunicode(target) self.translation = self.personality.encode(target or u"", self.encoding) target = property(gettarget, settarget) @property def encoding(self): if self._store: return self._store.encoding else: return self.personality.default_encoding def __str__(self): """Convert to a string. Double check that unicode is handled somehow here.""" source = self.getoutput() assert isinstance(source, unicode) return source.encode(self.encoding) def getoutput(self): """Convert the element back into formatted lines for a .properties file""" notes = self.getnotes() if notes: notes += u"\n" if self.isblank(): return notes + u"\n" else: self.value = self.personality.encode(self.source, self.encoding) self.translation = self.personality.encode(self.target, self.encoding) # encode key, if needed key = self.name kwc = self.personality.key_wrap_char if kwc: key = key.replace(kwc, '\\%s' % kwc) key = '%s%s%s' % (kwc, key, kwc) # encode value, if needed value = self.translation or self.value vwc = self.personality.value_wrap_char if vwc: value = value.replace(vwc, '\\%s' % vwc) value = '%s%s%s' % (vwc, value, vwc) wrappers = self.out_delimiter_wrappers delimiter = '%s%s%s' % (wrappers, self.delimiter, wrappers) ending = self.out_ending out_dict = { "notes": notes, "key": key, "del": delimiter, "value": value, "ending": ending, } return u"%(notes)s%(key)s%(del)s%(value)s%(ending)s\n" % out_dict def getlocations(self): return [self.name] def addnote(self, text, origin=None, position="append"): if origin in ['programmer', 'developer', 'source code', None]: text = data.forceunicode(text) self.comments.append(text) else: return super(propunit, self).addnote(text, origin=origin, position=position) def getnotes(self, origin=None): if origin in ['programmer', 'developer', 'source code', None]: return u'\n'.join(self.comments) else: return super(propunit, self).getnotes(origin) def removenotes(self): self.comments = [] def isblank(self): """returns whether this is a blank element, containing only comments.""" return not (self.name or self.value) def istranslatable(self): return bool(self.name) def getid(self): return self.name def setid(self, value): self.name = value class propfile(base.TranslationStore): """this class represents a .properties file, made up of propunits""" UnitClass = propunit def __init__(self, inputfile=None, personality="java", encoding=None): """construct a propfile, optionally reading in from inputfile""" super(propfile, self).__init__(unitclass=self.UnitClass) self.personality = get_dialect(personality) self.encoding = encoding or self.personality.default_encoding self.filename = getattr(inputfile, 'name', '') if inputfile is not None: propsrc = inputfile.read() inputfile.close() self.parse(propsrc) self.makeindex() def parse(self, propsrc): """Read the source of a properties file in and include them as units.""" text, encoding = self.detect_encoding(propsrc, default_encodings=[self.personality.default_encoding, 'utf-8', 'utf-16']) if not text: raise IOError("Cannot detect encoding for %s." % (self.filename or "given string")) self.encoding = encoding propsrc = text newunit = propunit("", self.personality.name) inmultilinevalue = False inmultilinecomment = False for line in propsrc.split(u"\n"): # handle multiline value if we're in one line = quote.rstripeol(line) if inmultilinevalue: newunit.value += line.lstrip() # see if there's more inmultilinevalue = is_line_continuation(newunit.value) # if we're still waiting for more... if inmultilinevalue: # strip the backslash newunit.value = newunit.value[:-1] if not inmultilinevalue: # we're finished, add it to the list... self.addunit(newunit) newunit = propunit("", self.personality.name) # otherwise, this could be a comment # FIXME handle // inline comments elif (inmultilinecomment or is_comment_one_line(line) or is_comment_start(line) or is_comment_end(line)): # add a comment if line not in self.personality.drop_comments: newunit.comments.append(line) if is_comment_start(line): inmultilinecomment = True elif is_comment_end(line): inmultilinecomment = False elif not line.strip(): # this is a blank line... if str(newunit).strip(): self.addunit(newunit) newunit = propunit("", self.personality.name) else: newunit.delimiter, delimiter_pos = self.personality.find_delimiter(line) if delimiter_pos == -1: newunit.name = self.personality.key_strip(line) newunit.value = u"" self.addunit(newunit) newunit = propunit("", self.personality.name) else: newunit.name = self.personality.key_strip(line[:delimiter_pos]) if is_line_continuation(line[delimiter_pos+1:].lstrip()): inmultilinevalue = True newunit.value = line[delimiter_pos+1:].lstrip()[:-1] else: newunit.value = self.personality.value_strip(line[delimiter_pos+1:]) self.addunit(newunit) newunit = propunit("", self.personality.name) # see if there is a leftover one... if inmultilinevalue or len(newunit.comments) > 0: self.addunit(newunit) def __str__(self): """Convert the units back to lines.""" lines = [] for unit in self.units: lines.append(unit.getoutput()) uret = u"".join(lines) return uret.encode(self.encoding) class javafile(propfile): Name = "Java Properties" Extensions = ['properties'] def __init__(self, *args, **kwargs): kwargs['personality'] = "java" kwargs['encoding'] = "auto" super(javafile, self).__init__(*args, **kwargs) class javautf8file(propfile): Name = "Java Properties (UTF-8)" Extensions = ['properties'] def __init__(self, *args, **kwargs): kwargs['personality'] = "java-utf8" kwargs['encoding'] = "utf-8" super(javautf8file, self).__init__(*args, **kwargs) class stringsfile(propfile): Name = "OS X Strings" Extensions = ['strings'] def __init__(self, *args, **kwargs): kwargs['personality'] = "strings" super(stringsfile, self).__init__(*args, **kwargs) class stringsutf8file(propfile): Name = "OS X Strings (UTF-8)" Extensions = ['strings'] def __init__(self, *args, **kwargs): kwargs['personality'] = "strings-utf8" kwargs['encoding'] = "utf-8" super(stringsutf8file, self).__init__(*args, **kwargs)
CantemoInternal/pyxb
refs/heads/next
pyxb/bundles/wssplat/xenc.py
6
from pyxb.bundles.wssplat.raw.xenc import *
jeffwidman/ansible-modules-core
refs/heads/devel
cloud/openstack/os_ironic_node.py
68
#!/usr/bin/python # coding: utf-8 -*- # (c) 2015, Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False from distutils.version import StrictVersion DOCUMENTATION = ''' --- module: os_ironic_node short_description: Activate/Deactivate Bare Metal Resources from OpenStack author: "Monty Taylor (@emonty)" extends_documentation_fragment: openstack version_added: "2.0" description: - Deploy to nodes controlled by Ironic. options: state: description: - Indicates desired state of the resource choices: ['present', 'absent'] default: present deploy: description: - Indicates if the resource should be deployed. Allows for deployment logic to be disengaged and control of the node power or maintenance state to be changed. choices: ['true', 'false'] default: true uuid: description: - globally unique identifier (UUID) to be given to the resource. required: false default: None ironic_url: description: - If noauth mode is utilized, this is required to be set to the endpoint URL for the Ironic API. Use with "auth" and "auth_type" settings set to None. required: false default: None config_drive: description: - A configdrive file or HTTP(S) URL that will be passed along to the node. required: false default: None instance_info: description: - Definition of the instance information which is used to deploy the node. This information is only required when an instance is set to present. suboptions: image_source: description: - An HTTP(S) URL where the image can be retrieved from. image_checksum: description: - The checksum of image_source. image_disk_format: description: - The type of image that has been requested to be deployed. power: description: - A setting to allow power state to be asserted allowing nodes that are not yet deployed to be powered on, and nodes that are deployed to be powered off. choices: ['present', 'absent'] default: present maintenance: description: - A setting to allow the direct control if a node is in maintenance mode. required: false default: false maintenance_reason: description: - A string expression regarding the reason a node is in a maintenance mode. required: false default: None wait: description: - A boolean value instructing the module to wait for node activation or deactivation to complete before returning. required: false default: False version_added: "2.1" timeout: description: - An integer value representing the number of seconds to wait for the node activation or deactivation to complete. version_added: "2.1" ''' EXAMPLES = ''' # Activate a node by booting an image with a configdrive attached os_ironic_node: cloud: "openstack" uuid: "d44666e1-35b3-4f6b-acb0-88ab7052da69" state: present power: present deploy: True maintenance: False config_drive: "http://192.168.1.1/host-configdrive.iso" instance_info: image_source: "http://192.168.1.1/deploy_image.img" image_checksum: "356a6b55ecc511a20c33c946c4e678af" image_disk_format: "qcow" delegate_to: localhost ''' def _choose_id_value(module): if module.params['uuid']: return module.params['uuid'] if module.params['name']: return module.params['name'] return None # TODO(TheJulia): Change this over to use the machine patch method # in shade once it is available. def _prepare_instance_info_patch(instance_info): patch = [] patch.append({ 'op': 'replace', 'path': '/instance_info', 'value': instance_info }) return patch def _is_true(value): true_values = [True, 'yes', 'Yes', 'True', 'true', 'present', 'on'] if value in true_values: return True return False def _is_false(value): false_values = [False, None, 'no', 'No', 'False', 'false', 'absent', 'off'] if value in false_values: return True return False def _check_set_maintenance(module, cloud, node): if _is_true(module.params['maintenance']): if _is_false(node['maintenance']): cloud.set_machine_maintenance_state( node['uuid'], True, reason=module.params['maintenance_reason']) module.exit_json(changed=True, msg="Node has been set into " "maintenance mode") else: # User has requested maintenance state, node is already in the # desired state, checking to see if the reason has changed. if (str(node['maintenance_reason']) not in str(module.params['maintenance_reason'])): cloud.set_machine_maintenance_state( node['uuid'], True, reason=module.params['maintenance_reason']) module.exit_json(changed=True, msg="Node maintenance reason " "updated, cannot take any " "additional action.") elif _is_false(module.params['maintenance']): if node['maintenance'] is True: cloud.remove_machine_from_maintenance(node['uuid']) return True else: module.fail_json(msg="maintenance parameter was set but a valid " "the value was not recognized.") return False def _check_set_power_state(module, cloud, node): if 'power on' in str(node['power_state']): if _is_false(module.params['power']): # User has requested the node be powered off. cloud.set_machine_power_off(node['uuid']) module.exit_json(changed=True, msg="Power requested off") if 'power off' in str(node['power_state']): if (_is_false(module.params['power']) and _is_false(module.params['state'])): return False if (_is_false(module.params['power']) and _is_false(module.params['state'])): module.exit_json( changed=False, msg="Power for node is %s, node must be reactivated " "OR set to state absent" ) # In the event the power has been toggled on and # deployment has been requested, we need to skip this # step. if (_is_true(module.params['power']) and _is_false(module.params['deploy'])): # Node is powered down when it is not awaiting to be provisioned cloud.set_machine_power_on(node['uuid']) return True # Default False if no action has been taken. return False def main(): argument_spec = openstack_full_argument_spec( uuid=dict(required=False), name=dict(required=False), instance_info=dict(type='dict', required=False), config_drive=dict(required=False), ironic_url=dict(required=False), state=dict(required=False, default='present'), maintenance=dict(required=False), maintenance_reason=dict(required=False), power=dict(required=False, default='present'), deploy=dict(required=False, default=True), wait=dict(type='bool', required=False, default=False), timeout=dict(required=False, type='int', default=1800), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') if (module.params['wait'] and StrictVersion(shade.__version__) < StrictVersion('1.4.0')): module.fail_json(msg="To utilize wait, the installed version of" "the shade library MUST be >=1.4.0") if (module.params['auth_type'] in [None, 'None'] and module.params['ironic_url'] is None): module.fail_json(msg="Authentication appears disabled, Please " "define an ironic_url parameter") if (module.params['ironic_url'] and module.params['auth_type'] in [None, 'None']): module.params['auth'] = dict( endpoint=module.params['ironic_url'] ) node_id = _choose_id_value(module) if not node_id: module.fail_json(msg="A uuid or name value must be defined " "to use this module.") try: cloud = shade.operator_cloud(**module.params) node = cloud.get_machine(node_id) if node is None: module.fail_json(msg="node not found") uuid = node['uuid'] instance_info = module.params['instance_info'] changed = False wait = module.params['wait'] timeout = module.params['timeout'] # User has reqeusted desired state to be in maintenance state. if module.params['state'] is 'maintenance': module.params['maintenance'] = True if node['provision_state'] in [ 'cleaning', 'deleting', 'wait call-back']: module.fail_json(msg="Node is in %s state, cannot act upon the " "request as the node is in a transition " "state" % node['provision_state']) # TODO(TheJulia) This is in-development code, that requires # code in the shade library that is still in development. if _check_set_maintenance(module, cloud, node): if node['provision_state'] in 'active': module.exit_json(changed=True, result="Maintenance state changed") changed = True node = cloud.get_machine(node_id) if _check_set_power_state(module, cloud, node): changed = True node = cloud.get_machine(node_id) if _is_true(module.params['state']): if _is_false(module.params['deploy']): module.exit_json( changed=changed, result="User request has explicitly disabled " "deployment logic" ) if 'active' in node['provision_state']: module.exit_json( changed=changed, result="Node already in an active state." ) if instance_info is None: module.fail_json( changed=changed, msg="When setting an instance to present, " "instance_info is a required variable.") # TODO(TheJulia): Update instance info, however info is # deployment specific. Perhaps consider adding rebuild # support, although there is a known desire to remove # rebuild support from Ironic at some point in the future. patch = _prepare_instance_info_patch(instance_info) cloud.set_node_instance_info(uuid, patch) cloud.validate_node(uuid) if not wait: cloud.activate_node(uuid, module.params['config_drive']) else: cloud.activate_node( uuid, configdrive=module.params['config_drive'], wait=wait, timeout=timeout) # TODO(TheJulia): Add more error checking.. module.exit_json(changed=changed, result="node activated") elif _is_false(module.params['state']): if node['provision_state'] not in "deleted": cloud.purge_node_instance_info(uuid) if not wait: cloud.deactivate_node(uuid) else: cloud.deactivate_node( uuid, wait=wait, timeout=timeout) module.exit_json(changed=True, result="deleted") else: module.exit_json(changed=False, result="node not found") else: module.fail_json(msg="State must be present, absent, " "maintenance, off") except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == "__main__": main()
cnsoft/kbengine-cocos2dx
refs/heads/cocos2dx-cnsoft
kbe/res/scripts/common/Lib/test/test_reprlib.py
56
""" Test cases for the repr module Nick Mathewson """ import sys import os import shutil import unittest from test.support import run_unittest from reprlib import repr as r # Don't shadow builtin repr from reprlib import Repr from reprlib import recursive_repr def nestedTuple(nesting): t = () for i in range(nesting): t = (t,) return t class ReprTests(unittest.TestCase): def test_string(self): eq = self.assertEqual eq(r("abc"), "'abc'") eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'") s = "a"*30+"b"*30 expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) eq(r("\"'"), repr("\"'")) s = "\""*30+"'"*100 expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) def test_tuple(self): eq = self.assertEqual eq(r((1,)), "(1,)") t3 = (1, 2, 3) eq(r(t3), "(1, 2, 3)") r2 = Repr() r2.maxtuple = 2 expected = repr(t3)[:-2] + "...)" eq(r2.repr(t3), expected) def test_container(self): from array import array from collections import deque eq = self.assertEqual # Tuples give up after 6 elements eq(r(()), "()") eq(r((1,)), "(1,)") eq(r((1, 2, 3)), "(1, 2, 3)") eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)") eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)") # Lists give up after 6 as well eq(r([]), "[]") eq(r([1]), "[1]") eq(r([1, 2, 3]), "[1, 2, 3]") eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]") eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]") # Sets give up after 6 as well eq(r(set([])), "set([])") eq(r(set([1])), "set([1])") eq(r(set([1, 2, 3])), "set([1, 2, 3])") eq(r(set([1, 2, 3, 4, 5, 6])), "set([1, 2, 3, 4, 5, 6])") eq(r(set([1, 2, 3, 4, 5, 6, 7])), "set([1, 2, 3, 4, 5, 6, ...])") # Frozensets give up after 6 as well eq(r(frozenset([])), "frozenset([])") eq(r(frozenset([1])), "frozenset([1])") eq(r(frozenset([1, 2, 3])), "frozenset([1, 2, 3])") eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset([1, 2, 3, 4, 5, 6])") eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset([1, 2, 3, 4, 5, 6, ...])") # collections.deque after 6 eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])") # Dictionaries give up after 4. eq(r({}), "{}") d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4} eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}") d['arthur'] = 1 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}") # array.array after 5. eq(r(array('i')), "array('i', [])") eq(r(array('i', [1])), "array('i', [1])") eq(r(array('i', [1, 2])), "array('i', [1, 2])") eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])") eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])") eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])") eq(r(array('i', [1, 2, 3, 4, 5, 6])), "array('i', [1, 2, 3, 4, 5, ...])") def test_numbers(self): eq = self.assertEqual eq(r(123), repr(123)) eq(r(123), repr(123)) eq(r(1.0/3), repr(1.0/3)) n = 10**100 expected = repr(n)[:18] + "..." + repr(n)[-19:] eq(r(n), expected) def test_instance(self): eq = self.assertEqual i1 = ClassWithRepr("a") eq(r(i1), repr(i1)) i2 = ClassWithRepr("x"*1000) expected = repr(i2)[:13] + "..." + repr(i2)[-14:] eq(r(i2), expected) i3 = ClassWithFailingRepr() eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3))) s = r(ClassWithFailingRepr) self.assertTrue(s.startswith("<class ")) self.assertTrue(s.endswith(">")) self.assertIn(s.find("..."), [12, 13]) def test_lambda(self): self.assertTrue(repr(lambda x: x).startswith( "<function <lambda")) # XXX anonymous functions? see func_repr def test_builtin_function(self): eq = self.assertEqual # Functions eq(repr(hash), '<built-in function hash>') # Methods self.assertTrue(repr(''.split).startswith( '<built-in method split of str object at 0x')) def test_range(self): eq = self.assertEqual eq(repr(range(1)), 'range(0, 1)') eq(repr(range(1, 2)), 'range(1, 2)') eq(repr(range(1, 4, 3)), 'range(1, 4, 3)') def test_nesting(self): eq = self.assertEqual # everything is meant to give up after 6 levels. eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]") eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]") eq(r(nestedTuple(6)), "(((((((),),),),),),)") eq(r(nestedTuple(7)), "(((((((...),),),),),),)") eq(r({ nestedTuple(5) : nestedTuple(5) }), "{((((((),),),),),): ((((((),),),),),)}") eq(r({ nestedTuple(6) : nestedTuple(6) }), "{((((((...),),),),),): ((((((...),),),),),)}") eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]") eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]") def test_cell(self): # XXX Hmm? How to get at a cell object? pass def test_descriptors(self): eq = self.assertEqual # method descriptors eq(repr(dict.items), "<method 'items' of 'dict' objects>") # XXX member descriptors # XXX attribute descriptors # XXX slot descriptors # static and class methods class C: def foo(cls): pass x = staticmethod(C.foo) self.assertTrue(repr(x).startswith('<staticmethod object at 0x')) x = classmethod(C.foo) self.assertTrue(repr(x).startswith('<classmethod object at 0x')) def test_unsortable(self): # Repr.repr() used to call sorted() on sets, frozensets and dicts # without taking into account that not all objects are comparable x = set([1j, 2j, 3j]) y = frozenset(x) z = {1j: 1, 2j: 2} r(x) r(y) r(z) def touch(path, text=''): fp = open(path, 'w') fp.write(text) fp.close() class LongReprTest(unittest.TestCase): def setUp(self): longname = 'areallylongpackageandmodulenametotestreprtruncation' self.pkgname = os.path.join(longname) self.subpkgname = os.path.join(longname, longname) # Make the package and subpackage shutil.rmtree(self.pkgname, ignore_errors=True) os.mkdir(self.pkgname) touch(os.path.join(self.pkgname, '__init__.py')) shutil.rmtree(self.subpkgname, ignore_errors=True) os.mkdir(self.subpkgname) touch(os.path.join(self.subpkgname, '__init__.py')) # Remember where we are self.here = os.getcwd() sys.path.insert(0, self.here) def tearDown(self): actions = [] for dirpath, dirnames, filenames in os.walk(self.pkgname): for name in dirnames + filenames: actions.append(os.path.join(dirpath, name)) actions.append(self.pkgname) actions.sort() actions.reverse() for p in actions: if os.path.isdir(p): os.rmdir(p) else: os.remove(p) del sys.path[0] def test_module(self): eq = self.assertEqual touch(os.path.join(self.subpkgname, self.pkgname + '.py')) from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation eq(repr(areallylongpackageandmodulenametotestreprtruncation), "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__)) eq(repr(sys), "<module 'sys' (built-in)>") def test_type(self): eq = self.assertEqual touch(os.path.join(self.subpkgname, 'foo.py'), '''\ class foo(object): pass ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo eq(repr(foo.foo), "<class '%s.foo'>" % foo.__name__) def test_object(self): # XXX Test the repr of a type with a really long tp_name but with no # tp_repr. WIBNI we had ::Inline? :) pass def test_class(self): touch(os.path.join(self.subpkgname, 'bar.py'), '''\ class bar: pass ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar # Module name may be prefixed with "test.", depending on how run. self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__) def test_instance(self): touch(os.path.join(self.subpkgname, 'baz.py'), '''\ class baz: pass ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz ibaz = baz.baz() self.assertTrue(repr(ibaz).startswith( "<%s.baz object at 0x" % baz.__name__)) def test_method(self): eq = self.assertEqual touch(os.path.join(self.subpkgname, 'qux.py'), '''\ class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: def amethod(self): pass ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux # Unbound methods first self.assertTrue(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod).startswith( '<function amethod')) # Bound method next iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() self.assertTrue(repr(iqux.amethod).startswith( '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \ % (qux.__name__,) )) def test_builtin_function(self): # XXX test built-in functions and methods with really long names pass class ClassWithRepr: def __init__(self, s): self.s = s def __repr__(self): return "ClassWithRepr(%r)" % self.s class ClassWithFailingRepr: def __repr__(self): raise Exception("This should be caught by Repr.repr_instance") class MyContainer: 'Helper class for TestRecursiveRepr' def __init__(self, values): self.values = list(values) def append(self, value): self.values.append(value) @recursive_repr() def __repr__(self): return '<' + ', '.join(map(str, self.values)) + '>' class MyContainer2(MyContainer): @recursive_repr('+++') def __repr__(self): return '<' + ', '.join(map(str, self.values)) + '>' class TestRecursiveRepr(unittest.TestCase): def test_recursive_repr(self): m = MyContainer(list('abcde')) m.append(m) m.append('x') m.append(m) self.assertEqual(repr(m), '<a, b, c, d, e, ..., x, ...>') m = MyContainer2(list('abcde')) m.append(m) m.append('x') m.append(m) self.assertEqual(repr(m), '<a, b, c, d, e, +++, x, +++>') def test_main(): run_unittest(ReprTests) run_unittest(LongReprTest) run_unittest(TestRecursiveRepr) if __name__ == "__main__": test_main()
DataDog/integrations-core
refs/heads/master
win32_event_log/datadog_checks/win32_event_log/check.py
1
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import re import pywintypes import win32con import win32event import win32evtlog import win32security from six import PY2 from datadog_checks.base import AgentCheck, ConfigurationError, is_affirmative from datadog_checks.base.utils.common import exclude_undefined_keys from datadog_checks.base.utils.time import get_timestamp from .filters import construct_xpath_query from .legacy import Win32EventLogWMI if PY2: ConfigMixin = object else: from .config_models import ConfigMixin class Win32EventLogCheck(AgentCheck, ConfigMixin): # The lower cased version of the `API SOURCE ATTRIBUTE` column from the table located here: # https://docs.datadoghq.com/integrations/faq/list-of-api-source-attribute-value/ SOURCE_TYPE_NAME = 'event viewer' # NOTE: Keep this in sync with config spec: # instances.start.value.enum # # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_subscribe_flags START_OPTIONS = { 'now': win32evtlog.EvtSubscribeToFutureEvents, 'oldest': win32evtlog.EvtSubscribeStartAtOldestRecord, } # NOTE: Keep this in sync with config spec: # instances.auth_type.value.enum # # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_rpc_login_flags LOGIN_FLAGS = { 'default': win32evtlog.EvtRpcLoginAuthDefault, 'negotiate': win32evtlog.EvtRpcLoginAuthNegotiate, 'kerberos': win32evtlog.EvtRpcLoginAuthKerberos, 'ntlm': win32evtlog.EvtRpcLoginAuthNTLM, } LEGACY_PARAMS = ( 'host', 'log_file', 'source_name', 'type', 'event_id', 'message_filters', 'event_format', ) # https://docs.microsoft.com/en-us/windows/win32/wes/eventmanifestschema-leveltype-complextype#remarks # # From # https://docs.microsoft.com/en-us/windows/win32/wes/eventmanifestschema-eventdefinitiontype-complextype#attributes: # # > If you do not specify a level, the event descriptor will contain a zero for level. LEVEL_TO_ALERT_TYPE = {0: 'info', 1: 'error', 2: 'error', 3: 'warning', 4: 'info', 5: 'info'} def __new__(cls, name, init_config, instances): instance = instances[0] if PY2 or is_affirmative(instance.get('legacy_mode', True)): return Win32EventLogWMI(name, init_config, instances) else: return super(Win32EventLogCheck, cls).__new__(cls) def __init__(self, name, init_config, instances): super(Win32EventLogCheck, self).__init__(name, init_config, instances) # Raw user-defined query or one we construct based on filters self._query = None # Create a pull subscription and its signaler on the first check run self._subscription = None self._event_handle = None # Cache a handle to the System event deserialization request self._render_context_system = None # Cache a handle to the EventData/UserData event deserialization request self._render_context_data = None # Create a bookmark handle which will be updated on saves to disk self._bookmark_handle = None # Session used for remote connections, or None if local connection self._session = None # Whether or not to interpret messages for unknown sources self._interpret_messages = is_affirmative( self.instance.get('interpret_messages', self.init_config.get('interpret_messages', True)) ) # These will become compiled regular expressions if any relevant patterns are defined in the config self._included_messages = None self._excluded_messages = None self._event_priority = self.instance.get('event_priority', self.init_config.get('event_priority', 'normal')) self.check_initializations.append(self.parse_config) self.check_initializations.append(self.construct_query) self.check_initializations.append(self.create_session) self.check_initializations.append(self.create_subscription) # Define every property collector self._collectors = [self.collect_timestamp, self.collect_fqdn, self.collect_level, self.collect_provider] if is_affirmative(self.instance.get('tag_event_id', self.init_config.get('tag_event_id', False))): self._collectors.append(self.collect_event_id) if is_affirmative(self.instance.get('tag_sid', self.init_config.get('tag_sid', False))): self._collectors.append(self.collect_sid) for legacy_param in self.LEGACY_PARAMS: if legacy_param in self.instance: self.log.warning( "%s config option is ignored unless running legacy mode. Please remove it", legacy_param ) def check(self, _): for event in self.consume_events(): try: rendered_event = self.render_event(event, self._render_context_system) except Exception as e: self.log.error('Unable to render event: %s', e) continue # Build up the event payload event_payload = { 'source_type_name': self.SOURCE_TYPE_NAME, 'priority': self._event_priority, 'tags': list(self.config.tags), } # As seen in every collector, before using members of the enum you need to check for existence. See: # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_system_property_id # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ns-winevt-evt_variant for collector in self._collectors: # Any collector may indicate that events need to be filtered out by returning False if collector(event_payload, rendered_event, event) is False: break else: self.event(event_payload) def collect_timestamp(self, event_payload, rendered_event, event_object): value, variant = rendered_event[win32evtlog.EvtSystemTimeCreated] if variant == win32evtlog.EvtVarTypeNull: event_payload['timestamp'] = get_timestamp() return event_payload['timestamp'] = get_timestamp(value) def collect_fqdn(self, event_payload, rendered_event, event_object): value, variant = rendered_event[win32evtlog.EvtSystemComputer] if variant == win32evtlog.EvtVarTypeNull or self._session is None: event_payload['host'] = self.hostname return event_payload['host'] = value def collect_level(self, event_payload, rendered_event, event_object): value, variant = rendered_event[win32evtlog.EvtSystemLevel] if variant == win32evtlog.EvtVarTypeNull: return event_payload['alert_type'] = self.LEVEL_TO_ALERT_TYPE.get(value, 'error') def collect_provider(self, event_payload, rendered_event, event_object): value, variant = rendered_event[win32evtlog.EvtSystemProviderName] if variant == win32evtlog.EvtVarTypeNull: return event_payload['aggregation_key'] = value event_payload['msg_title'] = '{}/{}'.format(self.config.path, value) message = None # See https://docs.microsoft.com/en-us/windows/win32/wes/getting-a-provider-s-metadata- try: # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtopenpublishermetadata metadata = win32evtlog.EvtOpenPublisherMetadata(value) # Code 2: The system cannot find the file specified. except pywintypes.error as e: if self._interpret_messages: message = self.interpret_message(event_object) else: self.log_windows_error(e) else: # no cov try: # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtformatmessage # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_format_message_flags message = win32evtlog.EvtFormatMessage(metadata, event_object, win32evtlog.EvtFormatMessageEvent) # Code 15027: The message resource is present but the message was not found in the message table. # Code 15028: The message ID for the desired message could not be found. except pywintypes.error as e: if self._interpret_messages: message = self.interpret_message(event_object) else: self.log_windows_error(e) if message is not None: message = self.sanitize_message(message.rstrip()) if self.message_filtered(message): return False event_payload['msg_text'] = message def collect_event_id(self, event_payload, rendered_event, event_object): # https://docs.microsoft.com/en-us/windows/win32/eventlog/event-identifiers value, variant = rendered_event[win32evtlog.EvtSystemEventID] if variant == win32evtlog.EvtVarTypeNull: return # Beware of documentation # # According to https://docs.microsoft.com/en-us/windows/win32/wes/eventschema-systempropertiestype-complextype # # > A legacy provider uses a 32-bit number to identify its events. If the event is logged by # a legacy provider, the value of EventID element contains the low-order 16 bits of the event # identifier and the Qualifier attribute contains the high-order 16 bits of the event identifier. # # The implication is that the real value is something like: (qualifier << 16) | event_id # # However, that is referring to an entirely different struct which we do not use: # https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-eventlogrecord event_payload['tags'].append('event_id:{}'.format(value)) def collect_sid(self, event_payload, rendered_event, event_object): value, variant = rendered_event[win32evtlog.EvtSystemUserID] if variant == win32evtlog.EvtVarTypeNull: return try: # https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupaccountsida # http://timgolden.me.uk/pywin32-docs/win32security__LookupAccountSid_meth.html user, domain, _ = win32security.LookupAccountSid( None if self._session is None else event_payload['host'], value ) except win32security.error as e: self.log_windows_error(e) else: event_payload['tags'].append('sid:{}\\{}'.format(domain, user)) def render_event(self, event, context): # See https://docs.microsoft.com/en-us/windows/win32/wes/rendering-events # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtrender # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_render_flags # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtRender_meth.html return win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventValues, Context=context) def consume_events(self): # Define out here and let loop shadow so we can update the bookmark one final time at the end of the check run event = None events_since_last_bookmark = 0 for event in self.poll_events(): events_since_last_bookmark += 1 if events_since_last_bookmark >= self.config.bookmark_frequency: events_since_last_bookmark = 0 self.update_bookmark(event) yield event if events_since_last_bookmark: self.update_bookmark(event) def poll_events(self): while True: # IMPORTANT: the subscription starts immediately so you must consume before waiting for the first signal while True: # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtnext # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtNext_meth.html # # An error saying EvtNext: The operation identifier is not valid happens # when you call the method and there are no events to read (i.e. polling). # There is an unreleased upstream contribution to return # an empty tuple instead https://github.com/mhammond/pywin32/pull/1648 # For the moment is logged as a debug line. try: events = win32evtlog.EvtNext(self._subscription, self.config.payload_size) except pywintypes.error as e: self.log_windows_error(e) break else: if not events: break for event in events: yield event # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobjectex # http://timgolden.me.uk/pywin32-docs/win32event__WaitForSingleObjectEx_meth.html wait_signal = win32event.WaitForSingleObjectEx(self._event_handle, self.config.timeout, True) # No more events, end check run if wait_signal != win32con.WAIT_OBJECT_0: break def update_bookmark(self, event): # See https://docs.microsoft.com/en-us/windows/win32/wes/bookmarking-events # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtupdatebookmark # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtUpdateBookmark_meth.html win32evtlog.EvtUpdateBookmark(self._bookmark_handle, event) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtrender # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtRender_meth.html bookmark_xml = win32evtlog.EvtRender(self._bookmark_handle, win32evtlog.EvtRenderBookmark) self.write_persistent_cache('bookmark', bookmark_xml) def parse_config(self): for option in ('included_messages', 'excluded_messages'): if option not in self.instance: continue pattern, error = self._compile_patterns(self.instance[option]) if error is not None: raise ConfigurationError('Error compiling pattern for option `{}`: {}'.format(option, error)) setattr(self, '_{}'.format(option), pattern) password = self.config.password if password: self.register_secret(password) def construct_query(self): query = self.config.query if query: self._query = query return self._query = construct_xpath_query(exclude_undefined_keys(self.config.filters.dict())) self.log.debug('Using constructed query: %s', self._query) def create_session(self): session_struct = self.get_session_struct() # No need for a remote connection if session_struct is None: return # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtopensession # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtOpenSession_meth.html self._session = win32evtlog.EvtOpenSession(session_struct, win32evtlog.EvtRpcLogin, 0, 0) def create_subscription(self): # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventa # http://timgolden.me.uk/pywin32-docs/win32event__CreateEvent_meth.html self._event_handle = win32event.CreateEvent(None, 0, 0, self.check_id) bookmark = self.read_persistent_cache('bookmark') if bookmark: flags = win32evtlog.EvtSubscribeStartAfterBookmark else: flags = self.START_OPTIONS[self.config.start] # Set explicitly to None rather than a potentially empty string bookmark = None # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtcreatebookmark # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtCreateBookmark_meth.html self._bookmark_handle = win32evtlog.EvtCreateBookmark(bookmark) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtsubscribe # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtSubscribe_meth.html self._subscription = win32evtlog.EvtSubscribe( self.config.path, flags, SignalEvent=self._event_handle, Query=self._query, Session=self._session, Bookmark=self._bookmark_handle if bookmark else None, ) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtcreaterendercontext # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_render_context_flags self._render_context_system = win32evtlog.EvtCreateRenderContext(win32evtlog.EvtRenderContextSystem) self._render_context_data = win32evtlog.EvtCreateRenderContext(win32evtlog.EvtRenderContextUser) def get_session_struct(self): server = self.instance.get('server', 'localhost') if server in ('localhost', '127.0.0.1'): return auth_type = self.instance.get('auth_type', 'default') if auth_type not in self.LOGIN_FLAGS: raise ConfigurationError('Invalid `auth_type`, must be one of: {}'.format(', '.join(self.LOGIN_FLAGS))) user = self.instance.get('user', self.instance.get('username')) domain = self.instance.get('domain') password = self.instance.get('password') # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ns-winevt-evt_rpc_login # http://timgolden.me.uk/pywin32-docs/PyEVT_RPC_LOGIN.html return server, user, domain, password, self.LOGIN_FLAGS[auth_type] def log_windows_error(self, exc): # http://timgolden.me.uk/pywin32-docs/error.html # # Occasionally the Windows function returns some extra data after a colon which we don't need self.log.debug('Error code %d when calling `%s`: %s', exc.winerror, exc.funcname.split(':')[0], exc.strerror) def message_filtered(self, message): return self._message_excluded(message) or not self._message_included(message) def _message_included(self, message): if self._included_messages is None: return True return not not self._included_messages.search(message) def _message_excluded(self, message): if self._excluded_messages is None: return False return not not self._excluded_messages.search(message) @staticmethod def _compile_patterns(patterns): valid_patterns = [] for pattern in patterns: # Ignore empty patterns as they match everything if not pattern: continue try: re.compile(pattern) except Exception as e: return None, str(e) else: valid_patterns.append(pattern) return re.compile('|'.join(valid_patterns)), None def interpret_message(self, event_object): rendered_event = self.render_event(event_object, self._render_context_data) lines = [] for value, variant in rendered_event: if variant != win32evtlog.EvtVarTypeString: break lines.append(value) if lines: return '\n'.join(lines) @staticmethod def sanitize_message(message): # https://github.com/mhammond/pywin32/pull/1524#issuecomment-633152961 return message.replace('\u200e', '') @staticmethod def render_event_xml(event): # no cov """ Helper function used only for debugging purposes. """ return win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml)
kmonsoor/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/test/encoded_modules/__init__.py
179
# -*- encoding: utf-8 -*- # This is a package that contains a number of modules that are used to # test import from the source files that have different encodings. # This file (the __init__ module of the package), is encoded in utf-8 # and contains a list of strings from various unicode planes that are # encoded differently to compare them to the same strings encoded # differently in submodules. The following list, test_strings, # contains a list of tuples. The first element of each tuple is the # suffix that should be prepended with 'module_' to arrive at the # encoded submodule name, the second item is the encoding and the last # is the test string. The same string is assigned to the variable # named 'test' inside the submodule. If the decoding of modules works # correctly, from module_xyz import test should result in the same # string as listed below in the 'xyz' entry. # module, encoding, test string test_strings = ( ('iso_8859_1', 'iso-8859-1', "Les hommes ont oublié cette vérité, " "dit le renard. Mais tu ne dois pas l'oublier. Tu deviens " "responsable pour toujours de ce que tu as apprivoisé."), ('koi8_r', 'koi8-r', "Познание бесконечности требует бесконечного времени.") )
xeddmc/PyBitmessage
refs/heads/master
src/class_singleCleaner.py
9
import threading import shared import time import sys import os import pickle import tr#anslate from helper_sql import * from debug import logger """ The singleCleaner class is a timer-driven thread that cleans data structures to free memory, resends messages when a remote node doesn't respond, and sends pong messages to keep connections alive if the network isn't busy. It cleans these data structures in memory: inventory (moves data to the on-disk sql database) inventorySets (clears then reloads data out of sql database) It cleans these tables on the disk: inventory (clears expired objects) pubkeys (clears pubkeys older than 4 weeks old which we have not used personally) It resends messages when there has been no response: resends getpubkey messages in 5 days (then 10 days, then 20 days, etc...) resends msg messages in 5 days (then 10 days, then 20 days, etc...) """ class singleCleaner(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): timeWeLastClearedInventoryAndPubkeysTables = 0 try: shared.maximumLengthOfTimeToBotherResendingMessages = (float(shared.config.get('bitmessagesettings', 'stopresendingafterxdays')) * 24 * 60 * 60) + (float(shared.config.get('bitmessagesettings', 'stopresendingafterxmonths')) * (60 * 60 * 24 *365)/12) except: # Either the user hasn't set stopresendingafterxdays and stopresendingafterxmonths yet or the options are missing from the config file. shared.maximumLengthOfTimeToBotherResendingMessages = float('inf') while True: shared.UISignalQueue.put(( 'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)')) with shared.inventoryLock: # If you use both the inventoryLock and the sqlLock, always use the inventoryLock OUTSIDE of the sqlLock. with SqlBulkExecute() as sql: for hash, storedValue in shared.inventory.items(): objectType, streamNumber, payload, expiresTime, tag = storedValue sql.execute( '''INSERT INTO inventory VALUES (?,?,?,?,?,?)''', hash, objectType, streamNumber, payload, expiresTime, tag) del shared.inventory[hash] shared.UISignalQueue.put(('updateStatusBar', '')) shared.broadcastToSendDataQueues(( 0, 'pong', 'no data')) # commands the sendData threads to send out a pong message if they haven't sent anything else in the last five minutes. The socket timeout-time is 10 minutes. # If we are running as a daemon then we are going to fill up the UI # queue which will never be handled by a UI. We should clear it to # save memory. if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): shared.UISignalQueue.queue.clear() if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380: timeWeLastClearedInventoryAndPubkeysTables = int(time.time()) sqlExecute( '''DELETE FROM inventory WHERE expirestime<? ''', int(time.time()) - (60 * 60 * 3)) # pubkeys sqlExecute( '''DELETE FROM pubkeys WHERE time<? AND usedpersonally='no' ''', int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys) # Let us resend getpubkey objects if we have not yet heard a pubkey, and also msg objects if we have not yet heard an acknowledgement queryreturn = sqlQuery( '''select toaddress, ackdata, status FROM sent WHERE ((status='awaitingpubkey' OR status='msgsent') AND folder='sent' AND sleeptill<? AND senttime>?) ''', int(time.time()), int(time.time()) - shared.maximumLengthOfTimeToBotherResendingMessages) for row in queryreturn: if len(row) < 2: with shared.printLock: sys.stderr.write( 'Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row)) time.sleep(3) break toAddress, ackData, status = row if status == 'awaitingpubkey': resendPubkeyRequest(toAddress) elif status == 'msgsent': resendMsg(ackData) # Let's also clear and reload shared.inventorySets to keep it from # taking up an unnecessary amount of memory. for streamNumber in shared.inventorySets: shared.inventorySets[streamNumber] = set() queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber) for row in queryData: shared.inventorySets[streamNumber].add(row[0]) with shared.inventoryLock: for hash, storedValue in shared.inventory.items(): objectType, streamNumber, payload, expiresTime, tag = storedValue if not streamNumber in shared.inventorySets: shared.inventorySets[streamNumber] = set() shared.inventorySets[streamNumber].add(hash) # Let us write out the knowNodes to disk if there is anything new to write out. if shared.needToWriteKnownNodesToDisk: shared.knownNodesLock.acquire() output = open(shared.appdata + 'knownnodes.dat', 'wb') try: pickle.dump(shared.knownNodes, output) output.close() except Exception as err: if "Errno 28" in str(err): logger.fatal('(while receiveDataThread shared.needToWriteKnownNodesToDisk) Alert: Your disk or data storage volume is full. ') shared.UISignalQueue.put(('alert', (tr.translateText("MainWindow", "Disk full"), tr.translateText("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True))) if shared.daemon: os._exit(0) shared.knownNodesLock.release() shared.needToWriteKnownNodesToDisk = False time.sleep(300) def resendPubkeyRequest(address): logger.debug('It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.') try: del shared.neededPubkeys[ address] # We need to take this entry out of the shared.neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently. except: pass shared.UISignalQueue.put(( 'updateStatusBar', 'Doing work necessary to again attempt to request a public key...')) sqlExecute( '''UPDATE sent SET status='msgqueued' WHERE toaddress=?''', address) shared.workerQueue.put(('sendmessage', '')) def resendMsg(ackdata): logger.debug('It has been a long time and we haven\'t heard an acknowledgement to our msg. Sending again.') sqlExecute( '''UPDATE sent SET status='msgqueued' WHERE ackdata=?''', ackdata) shared.workerQueue.put(('sendmessage', '')) shared.UISignalQueue.put(( 'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...'))
yamila-moreno/nikola
refs/heads/master
nikola/data/themes/base/messages/messages_bg.py
6
# -*- encoding:utf-8 -*- from __future__ import unicode_literals MESSAGES = { "%d min remaining to read": "", "(active)": "", "Also available in:": "Също достъпно в:", "Archive": "Архив", "Categories": "Категории", "Comments": "", "LANGUAGE": "Български", "Languages:": "", "More posts about %s": "Още публикации относно %s", "Newer posts": "Нови публикации", "Next post": "Следваща публикация", "No posts found.": "", "Nothing found.": "", "Older posts": "Стари публикации", "Original site": "Оригиналния сайт", "Posted:": "Публиковано:", "Posts about %s": "Публикации относно %s", "Posts for year %s": "Публикации за %s година", "Posts for {month} {day}, {year}": "", "Posts for {month} {year}": "Публикации за {month} {year}", "Previous post": "Предишна публикация", "Publication date": "", "RSS feed": "", "Read in English": "Прочетете на български", "Read more": "Прочети още", "Skip to main content": "", "Source": "Source", "Subcategories:": "", "Tags and Categories": "Тагове и Категории", "Tags": "Тагове", "Write your page here.": "", "Write your post here.": "", "old posts, page %d": "стари публикации, страница %d", "page %d": "страница %d", }
thdtjsdn/FreeCAD
refs/heads/master
src/Tools/MakeApp.py
38
#! python # -*- coding: utf-8 -*- # (c) 2003 Werner Mayer LGPL # Create a new application module import os,sys,string import FCFileTools import MakeAppTools if(len(sys.argv) != 2): sys.stdout.write("Please enter a name for your application.\n") sys.exit() Application = sys.argv[1] # create directory ../Mod/<Application> if not os.path.isdir("../Mod/"+Application): os.mkdir("../Mod/"+Application) else: sys.stdout.write(Application + " already exists. Please enter another name.\n") sys.exit() # copying files from _TEMPLATE_ to ../Mod/<Application> sys.stdout.write("Copying files...") MakeAppTools.copyTemplate("_TEMPLATE_","../Mod/"+Application,"_TEMPLATE_", Application) sys.stdout.write("Ok\n") # replace the _TEMPLATE_ string by <Application> sys.stdout.write("Modifying files...\n") MakeAppTools.replaceTemplate("../Mod/" + Application,"_TEMPLATE_",Application) # make the congigure script executable #os.chmod("../Mod/" + Application + "/configure", 0777); sys.stdout.write("Modifying files done.\n") sys.stdout.write(Application + " module created successfully.\n")
kenorb/BitTorrent
refs/heads/master
osx/hacking.py
2
from AppKit import * from time import time from gettext import gettext from khashmir.krpc import KRPC from khashmir.util import * from khashmir.khash import * from BitTorrent.bencode import bencode, bdecode from BitTorrent.Rerequester import DHTRerequester from copy import copy from BitTorrent import NewVersion import hotshot, hotshot.stats KRPC.noisy = 0 c = NSApp().delegate() dht = c.mt.dht rnd = file('/dev/urandom','r').read def agetxt(x): if x <= 60: return "0m" x /= 60 if x < 60: return "%dm" % x x /= 60 if x < 24: return "%dh" % x x /= 24 if x > 999: return "xx" return "%dd"%x def lastSeen(): l = [] i = 0 s = "" s+= dht.table.node.id.encode('base64') for bucket in dht.table.buckets: if bucket.min <= dht.table.node <= bucket.max: s+= "*" s+="%d-%d(%d/%d)- "%(i, 2**160 / (bucket.max - bucket.min), len([x for x in bucket.l if not x.invalid]), len(bucket.l)) def ls(a, b): if a.lastSeen > b.lastSeen: return 1 elif b.lastSeen > a.lastSeen: return -1 return 0 bucket.l.sort(ls) for id, ls, age, invalid in [(x.id.encode('base64')[:4], time() - x.lastSeen, time() - x.age, x.invalid) for x in bucket.l]: if not invalid: l.append((age, id)) s+= "%s-%s-%s, " % (agetxt(ls), id, agetxt(age)) s=s[:-2] s+= "\n--------------------------\n" i += 1 l.sort() print s + "estimated total: %s mean age: %s oldest: %s - %s" % (`dht.table.numPeers()`, agetxt(reduce(lambda a, b: a+b[0], l,0) / len(l)), l[-1][1], agetxt(l[-1][0])) ls = lastseen = lastSeen def dumpBuckets(): for bucket in dht.table.buckets: print bucket.l def getPeers(id): def p(v): print ">>>", [unpackPeers(x) for x in v] dht.getPeers(id, p) def downsizeBuckets(): dht.table.buckets = dht.table.buckets[0:1];dht.table.buckets[0].max=2**160 def gt(): __builtins__['_'] = gettext def showfuncs(): print [(time() - x[0], x[1]) for x in dht.rawserver.funcs] def drl(): print "%s items (%s/%s) %1.1f" % (len(dht.udp.rltransport.q), dht.udp.rltransport.dropped, dht.udp.rltransport.sent, dht.udp.rltransport.dropped*1.0/(dht.udp.rltransport.sent + dht.udp.rltransport.dropped)*100) def drs(): dht.udp.rltransport.sent = dht.udp.rltransport.dropped = 0 def ss(): l = [(x.encode('base64')[:4], len(y)) for x,y in dht.store.items()] def cmp(a,b): if a[1] > b[1]: return 1 elif a[1] < b[1]: return -1 return 0 l.sort(cmp) l.reverse() print "%s %s" % (len(dht.store), l) def stopProfiling(): c.profile.stop() c.profile.close() stats = hotshot.stats.load("BT.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) def totalTorrents(): l = [intify(x) for x in dht.store.keys()] l.sort() spread = l[-2] - l[1] width = 2**160 / spread print "have %s, width 1/%s, total: %s" % (len(dht.store), width, len(l[1:-1]) * width) def refreshBucket(n): b = dht.table.buckets[n] dht.findNode(newIDInRange(b.min, b.max), lambda a: a) def count(id): d = {} def cb(l): for x in l: d[x] = 1 if not l: print ">>> %s peers for id %s" % (len(d), id.encode('base64')[:4]) dht.getPeers(id, cb) gonoisy=1 def donoisy(): if gonoisy: drl();drs() dht.rawserver.external_add_task(300, donoisy) def p(v): print ">>>", `v` def hs(): print [len(x) for x in dht.udp.hammerlock.buckets] def switchtracker(t): x = t._rerequest t._rerequest = DHTRerequester(c.config, x.sched, x.howmany, x.connect, x.externalsched, x.amount_left, x.up, x.down, x.port, x.wanted_peerid, x.infohash, x.errorfunc, x.doneflag, x.upratefunc, x.downratefunc, x.ever_got_incoming, x.diefunc, x.successfunc, c.mt.dht) c.mt.rawserver.external_add_task(0, t._rerequest.begin) def checkVersion(test_new_version='', test_current_version = ''): if c.config.has_key('new_version'): test_new_version = c.config['new_version'] if c.config.has_key('current_version'): test_current_version = c.config['current_version'] try: c.vc = NewVersion.Updater(c.vcThreadWrap, c.alertNewVersion, lambda a: a, lambda a: a, c.versionCheckFailed, test_new_version=test_new_version, test_current_version=test_current_version) c.vc.check() except: import traceback traceback.print_exc()
pmarks-net/grpc
refs/heads/master
tools/run_tests/sanity/check_version.py
11
#!/usr/bin/env python2.7 # Copyright 2016, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import yaml import os import re import subprocess errors = 0 os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../../..')) # hack import paths to pick up extra code sys.path.insert(0, os.path.abspath('tools/buildgen/plugins')) from expand_version import Version try: branch_name = subprocess.check_output( 'git rev-parse --abbrev-ref HEAD', shell=True) except: print 'WARNING: not a git repository' branch_name = None if branch_name is not None: m = re.match(r'^release-([0-9]+)_([0-9]+)$', branch_name) if m: print 'RELEASE branch' # version number should align with the branched version check_version = lambda version: ( version.major == int(m.group(1)) and version.minor == int(m.group(2))) warning = 'Version key "%%s" value "%%s" should have a major version %s and minor version %s' % (m.group(1), m.group(2)) elif re.match(r'^debian/.*$', branch_name): # no additional version checks for debian branches check_version = lambda version: True else: # all other branches should have a -dev tag check_version = lambda version: version.tag == 'dev' warning = 'Version key "%s" value "%s" should have a -dev tag' else: check_version = lambda version: True with open('build.yaml', 'r') as f: build_yaml = yaml.load(f.read()) settings = build_yaml['settings'] top_version = Version(settings['version']) if not check_version(top_version): errors += 1 print warning % ('version', top_version) for tag, value in settings.iteritems(): if re.match(r'^[a-z]+_version$', tag): value = Version(value) if tag != 'core_version': if value.major != top_version.major: errors += 1 print 'major version mismatch on %s: %d vs %d' % (tag, value.major, top_version.major) if value.minor != top_version.minor: errors += 1 print 'minor version mismatch on %s: %d vs %d' % (tag, value.minor, top_version.minor) if not check_version(value): errors += 1 print warning % (tag, value) sys.exit(errors)
maraujop/django-crispy-forms
refs/heads/main
crispy_forms/tests/test_layout.py
1
import pytest from django import forms from django.forms.models import formset_factory, modelformset_factory from django.middleware.csrf import _get_new_csrf_string from django.shortcuts import render from django.template import Context, Template from django.urls import reverse from django.utils.translation import gettext_lazy as _ from crispy_forms.bootstrap import Field, InlineCheckboxes from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, ButtonHolder, Column, Div, Fieldset, Layout, MultiField, Row, Submit from crispy_forms.utils import render_crispy_form from .conftest import only_bootstrap, only_bootstrap3, only_bootstrap4, only_uni_form from .forms import ( AdvancedFileForm, CheckboxesSampleForm, CrispyEmptyChoiceTestModel, CrispyTestModel, FileForm, SampleForm, SampleForm2, SampleForm3, SampleForm4, SampleForm5, SampleForm6, SelectSampleForm, ) from .utils import contains_partial, parse_expected, parse_form def test_invalid_unicode_characters(settings): # Adds a BooleanField that uses non valid unicode characters "ñ" form_helper = FormHelper() form_helper.add_layout(Layout("españa")) template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": SampleForm(), "form_helper": form_helper}) settings.CRISPY_FAIL_SILENTLY = False with pytest.raises(Exception): template.render(c) def test_unicode_form_field(): class UnicodeForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["contraseña"] = forms.CharField() helper = FormHelper() helper.layout = Layout("contraseña") html = render_crispy_form(UnicodeForm()) assert 'id="id_contraseña"' in html def test_meta_extra_fields_with_missing_fields(): class FormWithMeta(SampleForm): class Meta: fields = ("email", "first_name", "last_name") form = FormWithMeta() # We remove email field on the go del form.fields["email"] form_helper = FormHelper() form_helper.layout = Layout("first_name") template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": form, "form_helper": form_helper}) html = template.render(c) assert "email" not in html def test_layout_unresolved_field(settings): form_helper = FormHelper() form_helper.add_layout(Layout("typo")) template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": SampleForm(), "form_helper": form_helper}) settings.CRISPY_FAIL_SILENTLY = False with pytest.raises(Exception): template.render(c) def test_double_rendered_field(settings): form_helper = FormHelper() form_helper.add_layout(Layout("is_company", "is_company")) template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": SampleForm(), "form_helper": form_helper}) settings.CRISPY_FAIL_SILENTLY = False with pytest.raises(Exception): template.render(c) def test_context_pollution(): class ExampleForm(forms.Form): comment = forms.CharField() form = ExampleForm() form2 = SampleForm() template = Template( """ {% load crispy_forms_tags %} {{ form.as_ul }} {% crispy form2 %} {{ form.as_ul }} """ ) c = Context({"form": form, "form2": form2}) html = template.render(c) assert html.count('name="comment"') == 2 assert html.count('name="is_company"') == 1 def test_layout_fieldset_row_html_with_unicode_fieldnames(settings): form_helper = FormHelper() form_helper.add_layout( Layout( Fieldset( "Company Data", "is_company", css_id="fieldset_company_data", css_class="fieldsets", title="fieldset_title", test_fieldset="123", ), Fieldset( "User Data", "email", Row( "password1", "password2", css_id="row_passwords", css_class="rows", ), HTML('<a href="#" id="testLink">test link</a>'), HTML( """ {% if flag %}{{ message }}{% endif %} """ ), "first_name", "last_name", ), ) ) template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": SampleForm(), "form_helper": form_helper, "flag": True, "message": "Hello!"}) html = template.render(c) assert 'id="fieldset_company_data"' in html assert 'class="fieldsets' in html assert 'title="fieldset_title"' in html assert 'test-fieldset="123"' in html assert 'id="row_passwords"' in html assert html.count("<label") == 6 if settings.CRISPY_TEMPLATE_PACK == "uni_form": assert 'class="formRow rows"' in html elif settings.CRISPY_TEMPLATE_PACK == "bootstrap4": assert 'class="form-row rows"' in html else: assert 'class="row rows"' in html assert "Hello!" in html assert "testLink" in html def test_change_layout_dynamically_delete_field(): template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) form = SampleForm() form_helper = FormHelper() form_helper.add_layout( Layout( Fieldset( "Company Data", "is_company", "email", "password1", "password2", css_id="multifield_info", ), Column( "first_name", "last_name", css_id="column_name", ), ) ) # We remove email field on the go # Layout needs to be adapted for the new form fields del form.fields["email"] del form_helper.layout.fields[0].fields[1] c = Context({"form": form, "form_helper": form_helper}) html = template.render(c) assert "email" not in html def test_column_has_css_classes(settings): template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) form = SampleForm() form_helper = FormHelper() form_helper.add_layout( Layout( Fieldset( "Company Data", "is_company", "email", "password1", "password2", css_id="multifield_info", ), Column("first_name", "last_name"), ) ) c = Context({"form": form, "form_helper": form_helper}) html = template.render(c) if settings.CRISPY_TEMPLATE_PACK == "uni_form": assert html.count("formColumn") == 1 assert html.count("col") == 0 elif settings.CRISPY_TEMPLATE_PACK == "bootstrap4": assert html.count("formColumn") == 0 assert html.count("col-md") == 1 @only_bootstrap4 def test_bs4_column_css_classes(settings): template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) form = SampleForm() form_helper = FormHelper() form_helper.add_layout( Layout( Column("first_name", "last_name"), Column("first_name", "last_name", css_class="col-sm"), Column("first_name", "last_name", css_class="mb-4"), ) ) c = Context({"form": form, "form_helper": form_helper}) html = template.render(c) assert html.count("col-md") == 2 assert html.count("col-sm") == 1 def test_formset_layout(settings): SampleFormSet = formset_factory(SampleForm, extra=3) formset = SampleFormSet() helper = FormHelper() helper.form_id = "thisFormsetRocks" helper.form_class = "formsets-that-rock" helper.form_method = "POST" helper.form_action = "simpleAction" helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", "is_company", "email", ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row("password1", "password2"), Fieldset("", "first_name", "last_name"), ) html = render_crispy_form(form=formset, helper=helper, context={"csrf_token": _get_new_csrf_string()}) # Check formset fields assert contains_partial(html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>') assert contains_partial( html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>' ) assert contains_partial( html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>' ) assert contains_partial( html, '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>' ) assert html.count("hidden") == 5 # Check form structure assert html.count("<form") == 1 assert html.count("csrfmiddlewaretoken") == 1 assert "formsets-that-rock" in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse("simpleAction") in html # Check form layout assert "Item 1" in html assert "Item 2" in html assert "Item 3" in html assert html.count("Note for first form only") == 1 if settings.CRISPY_TEMPLATE_PACK == "uni_form": assert html.count("formRow") == 3 elif settings.CRISPY_TEMPLATE_PACK in ("bootstrap3", "bootstrap4"): assert html.count("row") == 3 if settings.CRISPY_TEMPLATE_PACK == "bootstrap4": assert html.count("form-group") == 18 def test_modelformset_layout(): CrispyModelFormSet = modelformset_factory(CrispyTestModel, form=SampleForm4, extra=3) formset = CrispyModelFormSet(queryset=CrispyTestModel.objects.none()) helper = FormHelper() helper.layout = Layout("email") html = render_crispy_form(form=formset, helper=helper) assert html.count("id_form-0-id") == 1 assert html.count("id_form-1-id") == 1 assert html.count("id_form-2-id") == 1 assert contains_partial(html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>') assert contains_partial( html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>' ) assert contains_partial( html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>' ) assert html.count('name="form-0-email"') == 1 assert html.count('name="form-1-email"') == 1 assert html.count('name="form-2-email"') == 1 assert html.count('name="form-3-email"') == 0 assert html.count("password") == 0 def test_i18n(): template = Template( """ {% load crispy_forms_tags %} {% crispy form form.helper %} """ ) form = SampleForm() form_helper = FormHelper() form_helper.layout = Layout( HTML(_("i18n text")), Fieldset( _("i18n legend"), "first_name", "last_name", ), ) form.helper = form_helper html = template.render(Context({"form": form})) assert html.count("i18n legend") == 1 def test_default_layout(): test_form = SampleForm2() assert test_form.helper.layout.fields == [ "is_company", "email", "password1", "password2", "first_name", "last_name", "datetime_field", ] def test_default_layout_two(): test_form = SampleForm3() assert test_form.helper.layout.fields == ["email"] def test_modelform_layout_without_meta(): test_form = SampleForm4() test_form.helper = FormHelper() test_form.helper.layout = Layout("email") html = render_crispy_form(test_form) assert "email" in html assert "password" not in html def test_specialspaceless_not_screwing_intended_spaces(): # see issue #250 test_form = SampleForm() test_form.fields["email"].widget = forms.Textarea() test_form.helper = FormHelper() test_form.helper.layout = Layout("email", HTML("<span>first span</span> <span>second span</span>")) html = render_crispy_form(test_form) assert "<span>first span</span> <span>second span</span>" in html def test_choice_with_none_is_selected(): # see issue #701 model_instance = CrispyEmptyChoiceTestModel() model_instance.fruit = None test_form = SampleForm6(instance=model_instance) html = render_crispy_form(test_form) assert "checked" in html @only_uni_form def test_layout_composition(): form_helper = FormHelper() form_helper.add_layout( Layout( Layout( MultiField( "Some company data", "is_company", "email", css_id="multifield_info", ), ), Column( "first_name", # 'last_name', Missing a field on purpose css_id="column_name", css_class="columns", ), ButtonHolder( Submit("Save", "Save", css_class="button white"), ), Div( "password1", "password2", css_id="custom-div", css_class="customdivs", ), ) ) template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": SampleForm(), "form_helper": form_helper}) html = template.render(c) assert "multiField" in html assert "formColumn" in html assert 'id="multifield_info"' in html assert 'id="column_name"' in html assert 'class="formColumn columns"' in html assert 'class="buttonHolder">' in html assert 'input type="submit"' in html assert 'name="Save"' in html assert 'id="custom-div"' in html assert 'class="customdivs"' in html assert "last_name" not in html @only_uni_form def test_second_layout_multifield_column_buttonholder_submit_div(): form_helper = FormHelper() form_helper.add_layout( Layout( MultiField( "Some company data", "is_company", "email", css_id="multifield_info", title="multifield_title", multifield_test="123", ), Column( "first_name", "last_name", css_id="column_name", css_class="columns", ), ButtonHolder( Submit( "Save the world", "{{ value_var }}", css_class="button white", data_id="test", data_name="test" ), Submit("store", "Store results"), ), Div("password1", "password2", css_id="custom-div", css_class="customdivs", test_markup="123"), ) ) template = Template( """ {% load crispy_forms_tags %} {% crispy form form_helper %} """ ) c = Context({"form": SampleForm(), "form_helper": form_helper, "value_var": "Save"}) html = template.render(c) assert "multiField" in html assert "formColumn" in html assert 'id="multifield_info"' in html assert 'title="multifield_title"' in html assert 'multifield-test="123"' in html assert 'id="column_name"' in html assert 'class="formColumn columns"' in html assert 'class="buttonHolder">' in html assert 'input type="submit"' in html assert "button white" in html assert 'data-id="test"' in html assert 'data-name="test"' in html assert 'name="save-the-world"' in html assert 'value="Save"' in html assert 'name="store"' in html assert 'value="Store results"' in html assert 'id="custom-div"' in html assert 'class="customdivs"' in html assert 'test-markup="123"' in html @only_bootstrap def test_keepcontext_context_manager(settings): # Test case for issue #180 # Apparently it only manifest when using render_to_response this exact way form = CheckboxesSampleForm() form.helper = FormHelper() # We use here InlineCheckboxes as it updates context in an unsafe way form.helper.layout = Layout("checkboxes", InlineCheckboxes("alphacheckboxes"), "numeric_multiple_checkboxes") context = {"form": form} response = render(request=None, template_name="crispy_render_template.html", context=context) if settings.CRISPY_TEMPLATE_PACK == "bootstrap": assert response.content.count(b"checkbox inline") == 3 elif settings.CRISPY_TEMPLATE_PACK == "bootstrap3": assert response.content.count(b"checkbox-inline") == 3 elif settings.CRISPY_TEMPLATE_PACK == "bootstrap4": assert response.content.count(b"custom-control-inline") == 3 assert response.content.count(b"custom-checkbox") > 0 @only_bootstrap4 def test_use_custom_control_is_used_in_checkboxes(): form = CheckboxesSampleForm() form.helper = FormHelper() form.helper.layout = Layout( "checkboxes", InlineCheckboxes("alphacheckboxes"), "numeric_multiple_checkboxes", ) # form.helper.use_custom_control take default value which is True assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_use_custom_control_is_used_in_checkboxes_true.html" ) form.helper.use_custom_control = True assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_use_custom_control_is_used_in_checkboxes_true.html" ) form.helper.use_custom_control = False assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_use_custom_control_is_used_in_checkboxes_false.html" ) @only_bootstrap4 def test_use_custom_control_is_used_in_radio(): form = SampleForm5() form.helper = FormHelper() form.helper.layout = Layout( "radio_select", ) # form.helper.use_custom_control take default value which is True assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_use_custom_control_is_used_in_radio_true.html" ) form.helper.use_custom_control = True assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_use_custom_control_is_used_in_radio_true.html" ) form.helper.use_custom_control = False assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_use_custom_control_is_used_in_radio_false.html" ) @only_bootstrap4 @pytest.mark.parametrize( "use_custom_control, expected_html", [ (True, "bootstrap4/test_layout/test_use_custom_control_in_select_true.html"), (False, "bootstrap4/test_layout/test_use_custom_control_in_select_false.html"), ], ) def test_use_custom_control_in_select(use_custom_control, expected_html): form = SelectSampleForm() form.helper = FormHelper() form.helper.template_pack = "bootstrap4" form.helper.layout = Layout("select") form.helper.use_custom_control = use_custom_control assert parse_form(form) == parse_expected(expected_html) @only_bootstrap3 def test_form_inline(): form = SampleForm() form.helper = FormHelper() form.helper.form_class = "form-inline" form.helper.field_template = "bootstrap3/layout/inline_field.html" form.helper.layout = Layout( "email", "password1", "last_name", ) html = render_crispy_form(form) assert html.count('class="form-inline"') == 1 assert html.count('class="form-group"') == 3 assert html.count('<label for="id_email" class="sr-only') == 1 assert html.count('id="div_id_email" class="form-group"') == 1 assert html.count('placeholder="email"') == 1 assert html.count("</label> <input") == 3 @only_bootstrap4 def test_bootstrap4_form_inline(): form = SampleForm() form.helper = FormHelper() form.helper.form_class = "form-inline" form.helper.field_template = "bootstrap4/layout/inline_field.html" form.helper.layout = Layout("email", "password1", "last_name") html = render_crispy_form(form) assert html.count('class="form-inline"') == 1 assert html.count('class="input-group"') == 3 assert html.count('<label for="id_email" class="sr-only') == 1 assert html.count('id="div_id_email" class="input-group"') == 1 assert html.count('placeholder="email"') == 1 assert html.count("</label> <input") == 3 def test_update_attributes_class(): form = SampleForm() form.helper = FormHelper() form.helper.layout = Layout("email", Field("password1"), "password2") form.helper["password1"].update_attributes(css_class="hello") html = render_crispy_form(form) assert html.count(' class="hello textinput') == 1 form.helper = FormHelper() form.helper.layout = Layout( "email", Field("password1", css_class="hello"), "password2", ) form.helper["password1"].update_attributes(css_class="hello2") html = render_crispy_form(form) assert html.count(' class="hello hello2 textinput') == 1 @only_bootstrap4 def test_file_field(): form = FileForm() form.helper = FormHelper() form.helper.layout = Layout("clearable_file") assert parse_form(form) == parse_expected("bootstrap4/test_layout/test_file_field_clearable_custom_control.html") form.helper.use_custom_control = False assert parse_form(form) == parse_expected("bootstrap4/test_layout/test_file_field_clearable.html") form.helper.use_custom_control = True form.helper.layout = Layout("file_field") assert parse_form(form) == parse_expected("bootstrap4/test_layout/test_file_field_custom_control.html") form.helper.use_custom_control = False assert parse_form(form) == parse_expected("bootstrap4/test_layout/test_file_field_default.html") @only_bootstrap4 def test_file_field_with_custom_class(): form = AdvancedFileForm() form.helper = FormHelper() form.helper.layout = Layout("clearable_file") assert parse_form(form) == parse_expected( "bootstrap4/test_layout/test_file_field_with_custom_class_clearable.html" ) form.helper.layout = Layout("file_field") assert parse_form(form) == parse_expected("bootstrap4/test_layout/test_file_field_with_custom_class.html")
stamhe/p2pool-blackcoin
refs/heads/master
wstools/tests/test_t1.py
308
############################################################################ # Joshua R. Boverhof, David W. Robertson, LBNL # See LBNLCopyright for copyright notice! ########################################################################### import unittest import test_wsdl import utils def makeTestSuite(): suite = unittest.TestSuite() suite.addTest(test_wsdl.makeTestSuite("services_by_file")) return suite def main(): loader = utils.MatchTestLoader(True, None, "makeTestSuite") unittest.main(defaultTest="makeTestSuite", testLoader=loader) if __name__ == "__main__" : main()
FrankBian/kuma
refs/heads/master
vendor/packages/ipython/IPython/testing/plugin/dtexample.py
7
"""Simple example using doctests. This file just contains doctests both using plain python and IPython prompts. All tests should be loaded by nose. """ def pyfunc(): """Some pure python tests... >>> pyfunc() 'pyfunc' >>> import os >>> 2+3 5 >>> for i in range(3): ... print i, ... print i+1, ... 0 1 1 2 2 3 """ return 'pyfunc' def ipfunc(): """Some ipython tests... In [1]: import os In [3]: 2+3 Out[3]: 5 In [26]: for i in range(3): ....: print i, ....: print i+1, ....: 0 1 1 2 2 3 Examples that access the operating system work: In [1]: !echo hello hello In [2]: !echo hello > /tmp/foo In [3]: !cat /tmp/foo hello In [4]: rm -f /tmp/foo It's OK to use '_' for the last result, but do NOT try to use IPython's numbered history of _NN outputs, since those won't exist under the doctest environment: In [7]: 'hi' Out[7]: 'hi' In [8]: print repr(_) 'hi' In [7]: 3+4 Out[7]: 7 In [8]: _+3 Out[8]: 10 In [9]: ipfunc() Out[9]: 'ipfunc' """ return 'ipfunc' def ranfunc(): """A function with some random output. Normal examples are verified as usual: >>> 1+3 4 But if you put '# random' in the output, it is ignored: >>> 1+3 junk goes here... # random >>> 1+2 again, anything goes #random if multiline, the random mark is only needed once. >>> 1+2 You can also put the random marker at the end: # random >>> 1+2 # random .. or at the beginning. More correct input is properly verified: >>> ranfunc() 'ranfunc' """ return 'ranfunc' def random_all(): """A function where we ignore the output of ALL examples. Examples: # all-random This mark tells the testing machinery that all subsequent examples should be treated as random (ignoring their output). They are still executed, so if a they raise an error, it will be detected as such, but their output is completely ignored. >>> 1+3 junk goes here... >>> 1+3 klasdfj; >>> 1+2 again, anything goes blah... """ pass def iprand(): """Some ipython tests with random output. In [7]: 3+4 Out[7]: 7 In [8]: print 'hello' world # random In [9]: iprand() Out[9]: 'iprand' """ return 'iprand' def iprand_all(): """Some ipython tests with fully random output. # all-random In [7]: 1 Out[7]: 99 In [8]: print 'hello' world In [9]: iprand_all() Out[9]: 'junk' """ return 'iprand_all'
suyashphadtare/sajil-shopping
refs/heads/develop
shopping_cart/shopping_cart/doctype/shopping_cart_shipping_rule/__init__.py
12133432
PubuduSaneth/cnvScan
refs/heads/master
src/__init__.py
12133432
Kitware/girder
refs/heads/master
test/test_api_key.py
3
# -*- coding: utf-8 -*- import datetime import json import pytest from girder.constants import TokenScope from girder.exceptions import ValidationException from girder.models.api_key import ApiKey from girder.models.setting import Setting from girder.models.token import Token from girder.settings import SettingKey from pytest_girder.assertions import assertStatus, assertStatusOk @pytest.fixture def apiKey(server, user): # Create a new API key with full access resp = server.request('/api_key', method='POST', params={ 'name': 'test key' }, user=user) assertStatusOk(resp) apiKey = ApiKey().load(resp.json['_id'], force=True) yield apiKey def testListScopes(server): resp = server.request('/token/scopes') assertStatusOk(resp) assert resp.json == TokenScope.listScopes() assert 'custom' in resp.json assert isinstance(resp.json['custom'], list) assert 'adminCustom' in resp.json assert isinstance(resp.json['adminCustom'], list) for scope in resp.json['custom'] + resp.json['adminCustom']: assert 'id' in scope assert 'name' in scope assert 'description' in scope def testUserCannotAccessOtherApiKeys(server, admin, user): # Normal users shouldn't be able to request other users' keys resp = server.request('/api_key', params={'userId': admin['_id']}, user=user) assertStatus(resp, 403) assert resp.json['message'] == 'Administrator access required.' def testUserCanAccessTheirOwnApiKeys(server, user): # Users should be able to request their own keys resp = server.request('/api_key', params={'userId': user['_id']}, user=user) assertStatusOk(resp) assert resp.json == [] def testUserCanAccessApiKeysWithoutUserId(server, user): # Passing no user ID should work resp = server.request('/api_key', user=user) assertStatusOk(resp) assert resp.json == [] def testAdminCanAccessOtherUsersKeys(server, admin, user): # Admins should be able to see other users' keys resp = server.request('/api_key', params={'userId': user['_id']}, user=admin) assertStatusOk(resp) assert resp.json == [] def testApiKeyCreation(server, user, apiKey): assert apiKey['scope'] is None assert apiKey['name'] == 'test key' assert apiKey['lastUse'] is None assert apiKey['tokenDuration'] is None assert apiKey['active'] is True def testTokenCreation(server, user, apiKey): defaultDuration = Setting().get(SettingKey.COOKIE_LIFETIME) # Create a token using the key resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'], 'duration': defaultDuration + 1000 }) assertStatusOk(resp) token = Token().load( resp.json['authToken']['token'], force=True, objectId=False) # Make sure token has full user auth access assert token['userId'] == user['_id'] assert token['scope'] == [TokenScope.USER_AUTH] # Make sure the token references the API key used to create it assert token['apiKeyId'] == apiKey['_id'] # Make sure the token duration is not longer than the default duration = token['expires'] - token['created'] assert duration == datetime.timedelta(days=defaultDuration) def testTokenCreationDuration(server, user, apiKey): defaultDuration = Setting().get(SettingKey.COOKIE_LIFETIME) # We should be able to request a duration shorter than default resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'], 'duration': defaultDuration - 1 }) assertStatusOk(resp) token = Token().load( resp.json['authToken']['token'], force=True, objectId=False) duration = token['expires'] - token['created'] assert duration == datetime.timedelta(days=defaultDuration - 1) def testTokenCreatesUniqueTokens(server, user, apiKey): for _ in range(0, 2): resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'] }) assertStatusOk(resp) # We should have two tokens for this key q = { 'userId': user['_id'], 'apiKeyId': apiKey['_id'] } count = Token().find(q).count() assert count == 2 def testInactiveKeyStructure(server, user, apiKey): newScopes = [TokenScope.DATA_READ, TokenScope.DATA_WRITE] resp = server.request('/api_key/%s' % apiKey['_id'], params={ 'active': False, 'tokenDuration': 10, 'scope': json.dumps(newScopes) }, method='PUT', user=user) assertStatusOk(resp) # Make sure key itself didn't change assert resp.json['key'] == apiKey['key'] apiKey = ApiKey().load(resp.json['_id'], force=True) assert not apiKey['active'] assert apiKey['tokenDuration'] == 10 assert set(apiKey['scope']) == set(newScopes) def testInactiveKeysCannotCreateTokens(server, user, apiKey): newScopes = [TokenScope.DATA_READ, TokenScope.DATA_WRITE] resp = server.request('/api_key/%s' % apiKey['_id'], params={ 'active': False, 'tokenDuration': 10, 'scope': json.dumps(newScopes) }, method='PUT', user=user) assertStatusOk(resp) # We should not be able to create tokens for this key anymore resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'] }) assertStatus(resp, 400) assert resp.json['message'] == 'Invalid API key.' def testDeactivatingKeyDeletesAssociatedTokens(server, user, apiKey): resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'] }) assertStatusOk(resp) newScopes = [TokenScope.DATA_READ, TokenScope.DATA_WRITE] resp = server.request('/api_key/%s' % apiKey['_id'], params={ 'active': False, 'tokenDuration': 10, 'scope': json.dumps(newScopes) }, method='PUT', user=user) assertStatusOk(resp) # This should have deleted all corresponding tokens q = { 'userId': user['_id'], 'apiKeyId': apiKey['_id'] } count = Token().find(q).count() assert count == 0 def testReactivatedKeyCanCreateTokens(server, user, apiKey): newScopes = [TokenScope.DATA_READ, TokenScope.DATA_WRITE] resp = server.request('/api_key/%s' % apiKey['_id'], params={ 'active': False, 'tokenDuration': 10, 'scope': json.dumps(newScopes) }, method='PUT', user=user) assertStatusOk(resp) resp = server.request('/api_key/%s' % apiKey['_id'], params={ 'active': True }, method='PUT', user=user) assertStatusOk(resp) assert resp.json['key'] == apiKey['key'] apiKey = ApiKey().load(resp.json['_id'], force=True) # Should now be able to make tokens with 10 day duration resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'] }) assertStatusOk(resp) token = Token().load( resp.json['authToken']['token'], force=True, objectId=False) duration = token['expires'] - token['created'] assert duration == datetime.timedelta(days=10) assert set(token['scope']) == set(newScopes) def testApiKeyDeletionDeletesAssociatedTokens(server, user, apiKey): resp = server.request('/api_key/token', method='POST', params={ 'key': apiKey['key'] }) assertStatusOk(resp) q = { 'userId': user['_id'], 'apiKeyId': apiKey['_id'] } # Deleting the API key should delete the tokens made with it count = Token().find(q).count() assert count == 1 resp = server.request('/api_key/%s' % apiKey['_id'], method='DELETE', user=user) assertStatusOk(resp) count = Token().find(q).count() assert count == 0 def testScopeValidation(db, admin, user): # Make sure normal user cannot request admin scopes requestedScopes = [TokenScope.DATA_OWN, TokenScope.SETTINGS_READ] with pytest.raises(ValidationException, match='Invalid scopes: %s.$' % TokenScope.SETTINGS_READ): ApiKey().createApiKey(user=user, name='', scope=requestedScopes) # Make sure an unregistered scope cannot be set on an API key requestedScopes = [TokenScope.DATA_OWN, TokenScope.SETTINGS_READ, 'nonsense'] with pytest.raises(ValidationException, match='Invalid scopes: nonsense.$'): ApiKey().createApiKey(user=admin, name='', scope=requestedScopes) def testDisableApiKeysSetting(server, user): errMsg = 'API key functionality is disabled on this instance.' resp = server.request('/api_key', method='POST', user=user, params={ 'name': 'test key' }) assertStatusOk(resp) # Disable API keys Setting().set(SettingKey.API_KEYS, False) # Key should still exist key = ApiKey().load(resp.json['_id'], force=True, exc=True) # No longer possible to authenticate with existing key resp = server.request('/api_key/token', method='POST', params={ 'key': key['key'] }) assertStatus(resp, 400) assert resp.json['message'] == errMsg # No longer possible to create new keys resp = server.request('/api_key', method='POST', user=user, params={ 'name': 'should not work' }) assertStatus(resp, 400) assert resp.json['message'] == errMsg # Still possible to delete key resp = server.request('/api_key/%s' % key['_id'], method='DELETE', user=user) assertStatusOk(resp) assert ApiKey().load(key['_id'], force=True) is None
Darkyler/Piscine
refs/heads/master
softwareUI.py
1
# -*- coding: utf-8 -*- from Tkinter import * # MEMO: pour qu'un widget apparaisse il faut qu'il prenne en parametre du constructeur la fenetre principale # Les widgets: fenetre, label, boutons, champ de saisie, #creation d'une fenetre de base root_window = Tk() #creation d'un label contenant du texte label_field = Label(root_window, text="Welcome to LudoTech' :-)") # On affiche le label dans la fenêtre, pack() positionne notre label dans la fenetre label_field.pack() #Label pseudo label_pseudo=Label(root_window, text="Pseudo") label_pseudo.pack() #Champ de saisie var_pseudo = StringVar() text_line_pseudo = Entry(root_window,textvariable=var_pseudo, width=30) text_line_pseudo.pack() #Label mot de passe label_password=Label(root_window, text="Mot de passe") label_password.pack() #Champ de saisie mot de passe var_password = StringVar() text_line_password = Entry(root_window,textvariable=var_password, width=30, show="*") text_line_password.pack() #Bouton de connexion button_connexion=Button(root_window, text="Se connecter") button_connexion.pack() #Bouton quitter button_quit=Button(root_window, text="Quitter", command=root_window.destroy) button_quit.pack() #Frame test main_frame = Frame(root_window,width=640, height=480,borderwidth=1) main_frame.pack(fill=BOTH) #Label for main_frame main_frame_label=Label(main_frame, text="Main Frame window") # On démarre la boucle Tkinter qui s'interompt quand on ferme la fenêtre root_window.mainloop() # TO DO: Classes d'interface nécessaire à la génération de chaque écran
thaskell1/volatility
refs/heads/master
volatility/plugins/linux/kernel_opened_files.py
6
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published by the Free Software Foundation. You may not use, modify or # distribute this program under any other version of the GNU General # Public License. # # Volatility 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Volatility. If not, see <http://www.gnu.org/licenses/>. # """ @author: Andrew Case @license: GNU General Public License 2.0 @contact: atcuno@gmail.com @organization: """ import volatility.obj as obj import volatility.plugins.linux.common as linux_common import volatility.plugins.linux.pslist as linux_pslist class linux_kernel_opened_files(linux_common.AbstractLinuxCommand): """Lists files that are opened from within the kernel""" def _walk_node_hash(self, node): last_node = None cnt = 0 hash_offset = self.addr_space.profile.get_obj_offset("dentry", "d_hash") while node.is_valid() and node != last_node: if cnt > 0: yield node, cnt dentry = obj.Object("dentry", offset = node.v() - hash_offset, vm = self.addr_space) cnt = cnt + 1 last_node = node node = dentry.d_hash.next def _walk_node_node(self, node): last_node = None cnt = 0 while node.is_valid() and node != last_node: if cnt > 0: yield node, cnt cnt = cnt + 1 last_node = node node = node.next def _walk_node(self, node): last_node = None yield node, 0 for node, cnt in self._walk_node_node(node): yield node, cnt for node, cnt in self._walk_node_hash(node): yield node, cnt def _gather_dcache(self): d_hash_shift = obj.Object("unsigned int", offset =self.addr_space.profile.get_symbol("d_hash_shift"), vm = self.addr_space) loop_max = 1 << d_hash_shift d_htable_ptr = obj.Object("Pointer", offset = self.addr_space.profile.get_symbol("dentry_hashtable"), vm = self.addr_space) arr = obj.Object(theType = "Array", targetType = "hlist_bl_head", offset = d_htable_ptr, vm = self.addr_space, count = loop_max) hash_offset = self.addr_space.profile.get_obj_offset("dentry", "d_hash") dents = {} for list_head in arr: if not list_head.first.is_valid(): continue node = obj.Object("hlist_bl_node", offset = list_head.first & ~1, vm = self.addr_space) for node, cnt in self._walk_node(node): dents[node.v() - hash_offset] = 0 return dents def _compare_filps(self): dcache = self._gather_dcache() tasks = linux_pslist.linux_pslist(self._config).calculate() for task in tasks: for filp, i in task.lsof(): val = filp.dentry.v() if not val in dcache: yield val procs = linux_pslist.linux_pslist(self._config).calculate() for proc in procs: for vma in proc.get_proc_maps(): if vma.vm_file: val = vma.vm_file.dentry.v() if not val in dcache: yield val def calculate(self): linux_common.set_plugin_members(self) for dentry_offset in self._compare_filps(): dentry = obj.Object("dentry", offset = dentry_offset, vm = self.addr_space) if dentry.d_count > 0 and dentry.d_inode.is_reg() and dentry.d_flags == 128: yield dentry def render_text(self, outfd, data): self.table_header(outfd, [("Offset (V)", "[addrpad]"), ("Partial File Path", "")]) for dentry in data: self.table_row(outfd, dentry.obj_offset, dentry.get_partial_path())
Omegaphora/external_chromium_org
refs/heads/lp5.1
tools/python/google/gethash_timer.py
182
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Issue a series of GetHash requests to the SafeBrowsing servers and measure the response times. Usage: $ ./gethash_timer.py --period=600 --samples=20 --output=resp.csv --period (or -p): The amount of time (in seconds) to wait between GetHash requests. Using a value of more than 300 (5 minutes) to include the effect of DNS. --samples (or -s): The number of requests to issue. If this parameter is not specified, the test will run indefinitely. --output (or -o): The path to a file where the output will be written in CSV format: sample_number,response_code,elapsed_time_ms """ import getopt import httplib import sys import time _GETHASH_HOST = 'safebrowsing.clients.google.com' _GETHASH_REQUEST = ( '/safebrowsing/gethash?client=googleclient&appver=1.0&pver=2.1') # Global logging file handle. g_file_handle = None def IssueGetHash(prefix): '''Issue one GetHash request to the safebrowsing servers. Args: prefix: A 4 byte value to look up on the server. Returns: The HTTP response code for the GetHash request. ''' body = '4:4\n' + prefix h = httplib.HTTPConnection(_GETHASH_HOST) h.putrequest('POST', _GETHASH_REQUEST) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) response_code = h.getresponse().status h.close() return response_code def TimedGetHash(prefix): '''Measure the amount of time it takes to receive a GetHash response. Args: prefix: A 4 byte value to look up on the the server. Returns: A tuple of HTTP resonse code and the response time (in milliseconds). ''' start = time.time() response_code = IssueGetHash(prefix) return response_code, (time.time() - start) * 1000 def RunTimedGetHash(period, samples=None): '''Runs an experiment to measure the amount of time it takes to receive multiple responses from the GetHash servers. Args: period: A floating point value that indicates (in seconds) the delay between requests. samples: An integer value indicating the number of requests to make. If 'None', the test continues indefinitely. Returns: None. ''' global g_file_handle prefix = '\x50\x61\x75\x6c' sample_count = 1 while True: response_code, elapsed_time = TimedGetHash(prefix) LogResponse(sample_count, response_code, elapsed_time) sample_count += 1 if samples is not None and sample_count == samples: break time.sleep(period) def LogResponse(sample_count, response_code, elapsed_time): '''Output the response for one GetHash query. Args: sample_count: The current sample number. response_code: The HTTP response code for the GetHash request. elapsed_time: The round-trip time (in milliseconds) for the GetHash request. Returns: None. ''' global g_file_handle output_list = (sample_count, response_code, elapsed_time) print 'Request: %d, status: %d, elapsed time: %f ms' % output_list if g_file_handle is not None: g_file_handle.write(('%d,%d,%f' % output_list) + '\n') g_file_handle.flush() def SetupOutputFile(file_name): '''Open a file for logging results. Args: file_name: A path to a file to store the output. Returns: None. ''' global g_file_handle g_file_handle = open(file_name, 'w') def main(): period = 10 samples = None options, args = getopt.getopt(sys.argv[1:], 's:p:o:', ['samples=', 'period=', 'output=']) for option, value in options: if option == '-s' or option == '--samples': samples = int(value) elif option == '-p' or option == '--period': period = float(value) elif option == '-o' or option == '--output': file_name = value else: print 'Bad option: %s' % option return 1 try: print 'Starting Timed GetHash ----------' SetupOutputFile(file_name) RunTimedGetHash(period, samples) except KeyboardInterrupt: pass print 'Timed GetHash complete ----------' g_file_handle.close() if __name__ == '__main__': sys.exit(main())
drnextgis/QGIS
refs/heads/master
python/plugins/processing/algs/grass7/nviz7.py
5
# -*- coding: utf-8 -*- """ *************************************************************************** nviz7.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from future import standard_library standard_library.install_aliases() from builtins import str __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os import time from qgis.PyQt.QtGui import QIcon from qgis.core import QgsRasterLayer from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterMultipleInput from processing.core.parameters import ParameterExtent from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterRaster from .Grass7Utils import Grass7Utils from processing.tools.system import getNumExportedLayers from processing.tools import dataobjects pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) class nviz7(GeoAlgorithm): ELEVATION = 'ELEVATION' VECTOR = 'VECTOR' COLOR = 'COLOR' GRASS_REGION_EXTENT_PARAMETER = 'GRASS_REGION_PARAMETER' GRASS_REGION_CELLSIZE_PARAMETER = 'GRASS_REGION_CELLSIZE_PARAMETER' def __init__(self): GeoAlgorithm.__init__(self) self.showInModeler = False def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'grass.png')) def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('nviz7') self.group, self.i18n_group = self.trAlgorithm('Visualization(NVIZ)') self.addParameter(ParameterMultipleInput( nviz7.ELEVATION, self.tr('Raster file(s) for elevation'), dataobjects.TYPE_RASTER, True)) self.addParameter(ParameterMultipleInput( nviz7.VECTOR, self.tr('Vector lines/areas overlay file(s)'), dataobjects.TYPE_VECTOR_ANY, True)) self.addParameter(ParameterMultipleInput( nviz7.COLOR, self.tr('Raster file(s) for color'), dataobjects.TYPE_RASTER, True)) self.addParameter(ParameterExtent( nviz7.GRASS_REGION_EXTENT_PARAMETER, self.tr('GRASS region extent'))) self.addParameter(ParameterNumber( self.GRASS_REGION_CELLSIZE_PARAMETER, self.tr('GRASS region cellsize (leave 0 for default)'), 0, None, 0.0)) def processAlgorithm(self, progress): commands = [] vector = self.getParameterValue(self.VECTOR) elevation = self.getParameterValue(self.ELEVATION) color = self.getParameterValue(self.COLOR) region = \ str(self.getParameterValue(self.GRASS_REGION_EXTENT_PARAMETER)) regionCoords = region.split(',') command = 'g.region ' command += 'n=' + str(regionCoords[3]) command += ' s=' + str(regionCoords[2]) command += ' e=' + str(regionCoords[1]) command += ' w=' + str(regionCoords[0]) cellsize = self.getParameterValue(self.GRASS_REGION_CELLSIZE_PARAMETER) if cellsize: command += ' res=' + str(cellsize) else: command += ' res=' + str(self.getDefaultCellsize()) commands.append(command) command = 'nviz7' if vector: layers = vector.split(';') for layer in layers: (cmd, newfilename) = self.exportVectorLayer(layer) commands.append(cmd) vector = vector.replace(layer, newfilename) command += ' vector=' + vector.replace(';', ',') if color: layers = color.split(';') for layer in layers: (cmd, newfilename) = self.exportRasterLayer(layer) commands.append(cmd) color = color.replace(layer, newfilename) command += ' color=' + color.replace(';', ',') if elevation: layers = elevation.split(';') for layer in layers: (cmd, newfilename) = self.exportRasterLayer(layer) commands.append(cmd) elevation = elevation.replace(layer, newfilename) command += ' elevation=' + elevation.replace(';', ',') if elevation is None and vector is None: command += ' -q' commands.append(command) Grass7Utils.createTempMapset() Grass7Utils.executeGrass7(commands, progress) def getTempFilename(self): filename = 'tmp' + str(time.time()).replace('.', '') \ + str(getNumExportedLayers()) return filename def exportVectorLayer(self, layer): destFilename = self.getTempFilename() command = 'v.in.ogr' command += ' min_area=-1' command += ' input="' + os.path.dirname(layer) + '"' command += ' layer=' + os.path.basename(layer)[:-4] command += ' output=' + destFilename command += ' --overwrite -o' return (command, destFilename) def exportRasterLayer(self, layer): destFilename = self.getTempFilename() command = 'r.in.gdal' command += ' input="' + layer + '"' command += ' band=1' command += ' out=' + destFilename command += ' --overwrite -o' return (command, destFilename) def getDefaultCellsize(self): cellsize = 0 for param in self.parameters: if param.value: if isinstance(param, ParameterRaster): if isinstance(param.value, QgsRasterLayer): layer = param.value else: layer = dataobjects.getObjectFromUri(param.value) cellsize = max(cellsize, (layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width()) elif isinstance(param, ParameterMultipleInput): layers = param.value.split(';') for layername in layers: layer = dataobjects.getObjectFromUri(layername) if isinstance(layer, QgsRasterLayer): cellsize = max(cellsize, ( layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width()) if cellsize == 0: cellsize = 1 return cellsize
HoliestCow/ece692_deeplearning
refs/heads/master
project5/gru/gruDET.py
1
import tensorflow as tf import numpy as np import time import h5py import matplotlib.pyplot as plt # from sklearn.metrics import confusion_matrix # import itertools # from copy import deepcopy # import os # import os.path from collections import OrderedDict import pickle # import cPickle as pickle # from tensorflow.examples.tutorials.mnist import input_data # mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) class cnnMNIST(object): def __init__(self): self.lr = 1e-3 self.epochs = 50000 self.runname = 'grudet_ep{}_lr{}'.format(self.epochs, self.lr) self.build_graph() def onehot_labels(self, labels): out = np.zeros((labels.shape[0], 2)) for i in range(labels.shape[0]): out[i, :] = np.eye(2, dtype=int)[int(labels[i])] return out def onenothot_labels(self, labels): out = np.zeros((labels.shape[0],)) for i in range(labels.shape[0]): out[i] = np.argmax(labels[i, :]) return out def get_data(self): # data_norm = True # data_augmentation = False f = h5py.File('./sequential_dataset_balanced.h5', 'r') X = f['train'] X_test = f['test'] self.x_train = X self.x_test = X_test # NOTE: always use the keylist to get data self.data_keylist = list(X.keys()) return def batch(self, iterable, n=1, shuffle=True, small_test=True, usethesekeys = None, shortset=False): if shuffle: self.shuffle() if usethesekeys is None: keylist = self.data_keylist else: keylist = usethesekeys if shortset: keylist = usethesekeys[:1000] # l = len(iterable) for i in range(len(keylist)): x = np.array(iterable[keylist[i]]['measured_spectra']) y = np.array(iterable[keylist[i]]['labels']) mask = y >= 0.5 y[mask] = 1 z = np.ones((y.shape[0],)) z[mask] = 100000.0 y = self.onehot_labels(y) yield x, y, z def validation_batcher(self): f = h5py.File('./sequential_dataset_validation.h5', 'r') # f = h5py.File('/home/holiestcow/Documents/2017_fall/ne697_hayward/lecture/datacompetition/sequential_dataset_validation.h5', 'r') samplelist = list(f.keys()) # samplelist = samplelist[:10] for i in range(len(samplelist)): data = f[samplelist[i]] yield data def build_graph(self): self.x = tf.placeholder(tf.float32, shape=[None, 15, 1024]) self.y_ = tf.placeholder(tf.float32, shape=[None, 2]) self.weights = tf.placeholder(tf.float32, shape=[None]) num_units = 512 num_layers = 2 # dropout = tf.placeholder(tf.float32) cells = [] for _ in range(num_layers): cell = tf.contrib.rnn.GRUCell(num_units) # Or LSTMCell(num_units) # cell = tf.contrib.rnn.DropoutWrapper( # cell, output_keep_prob=1.0) cells.append(cell) cell = tf.contrib.rnn.MultiRNNCell(cells) output, state = tf.nn.dynamic_rnn(cell, self.x, dtype=tf.float32) output = tf.transpose(output, [1, 0, 2]) last = tf.gather(output, int(output.get_shape()[0]) - 1) out_size = self.y_.get_shape()[1].value y_conv = tf.contrib.layers.fully_connected( last, out_size) #, activation_fn=None) # self.y_conv = tf.nn.softmax(logit) # probably a mistake here ratio = 1.0 / 100.0 # ratio = 1.0 / ratio class_weight = tf.constant([ratio, 1.0 - ratio]) self.y_conv = tf.multiply(y_conv, class_weight) # shape [batch_size, 2] # self.loss = tf.nn.softmax_cross_entropy_with_logits( # logits=weighted_logits, labels=self.y_, name="xent_raw") # NOTE: Normal gru # self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.y_, logits=self.y_conv)) # NOTE Normal gru with summing instead of mean self.loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=self.y_, logits=self.y_conv)) # NOTE: Weighted gru # self.loss = tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(targets=self.y_, logits=self.y_conv, pos_weight=200.0)) # NOTE: Weighted gru with summing instead of mean # self.loss = tf.reduce_sum(tf.nn.weighted_cross_entropy_with_logits(targets=self.y_, logits=self.y_conv, pos_weight=5.0)) # self.loss = tf.reduce_sum(tf.losses.sparse_softmax_cross_entropy(labels=self.y_), logits=self.y_conv, weights=self.weights)) self.train_step = tf.train.AdamOptimizer(self.lr).minimize(self.loss) def shuffle(self): np.random.shuffle(self.data_keylist) return def train(self): self.sess = tf.Session() init = tf.global_variables_initializer() self.sess.run(init) self.eval() # creating evaluation a = time.time() for i in range(self.epochs): # batch = mnist.train.next_batch(50) x_generator = self.batch(self.x_train, shuffle=True) if i % 100 == 0 and i != 0: counter = 0 sum_acc = 0 sum_loss = 0 hits = 0 x_generator_test = self.batch(self.x_test, usethesekeys=list(self.x_test.keys()), shortset=True) for j, k, z in x_generator_test: accuracy, train_loss, prediction = self.sess.run([self.accuracy, self.loss, self.prediction],feed_dict={self.x: j, self.y_: k, self.weights: z}) sum_loss += np.sum(train_loss) hits += np.sum(prediction) sum_acc += np.sum(accuracy) counter += 1 b = time.time() print('step {}:\navg acc {}\navg loss {}\ntotalhits {}\ntime elapsed: {} s'.format(i,sum_acc / counter, sum_loss / counter, hits, b-a)) x, y, z = next(x_generator) # stop # for j in range(x.shape[1]): # spectra = x[7, j, :] # fig = plt.figure() # plt.plot(spectra) # fig.savefig('seqspec_{}'.format(j)) # plt.close() # print(y[7, :]) # stop self.sess.run([self.train_step], feed_dict={ self.x: x, self.y_: y, self.weights: z}) # self.shuffle() def eval(self): # self.time_index = np.arange(self.y_conv.get_shape()[0]) self.prediction = tf.argmax(self.y_conv, 1) truth = tf.argmax(self.y_, 1) correct_prediction = tf.equal(self.prediction, truth) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # def test_eval(self): # self.eval() # x_generator = self.batch(self.x_test, n=100, shuffle=False) # y_generator = self.batch(self.y_test, n=100, shuffle=False) # test_acc = [] # counter = 0 # for data in x_generator: # test_acc += [self.sess.run(self.accuracy, feed_dict={ # self.x: data, self.y_: next(y_generator), self.keep_prob: 1.0})] # total_test_acc = sum(test_acc) / float(len(test_acc)) # print('test accuracy %g' % total_test_acc) def weight_variable(self, shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(self, shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def hack_1dreshape(self, x): # expand its dimensionality to fit into conv2d tensor_expand = tf.expand_dims(x, 1) tensor_expand = tf.expand_dims(tensor_expand, -1) return tensor_expand def conv2d(self, x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(self, x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def get_label_predictions(self): x_batcher = self.batch(self.x_test, n=1000, shuffle=False, usethesekeys=list(self.x_test.keys())) # y_batcher = self.batch(self.y_test, n=1000, shuffle=False) predictions = [] correct_predictions = np.zeros((0, 2)) for x, y, z in x_batcher: temp_predictions = self.sess.run( self.prediction, feed_dict={self.x: x}) predictions += temp_predictions.tolist() correct_predictions = np.vstack((correct_predictions, y)) return predictions, correct_predictions # def plot_confusion_matrix(cm, classes, # normalize=False, # title='Confusion matrix', # cmap=plt.cm.Blues): # """ # This function prints and plots the confusion matrix. # Normalization can be applied by setting `normalize=True`. # """ # if normalize: # cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] # print("Normalized confusion matrix") # else: # print('Confusion matrix, without normalization') # # print(cm) # # plt.imshow(cm, interpolation='nearest', cmap=cmap) # plt.title(title) # plt.colorbar() # tick_marks = np.arange(len(classes)) # plt.xticks(tick_marks, classes, rotation=45) # plt.yticks(tick_marks, classes) # # fmt = '.2f' if normalize else 'd' # thresh = cm.max() / 2. # for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): # plt.text(j, i, format(cm[i, j], fmt), # horizontalalignment="center", # color="white" if cm[i, j] > thresh else "black") # # plt.tight_layout() # plt.ylabel('True label') # plt.xlabel('Predicted label') def save_obj(obj, name ): with open('obj/'+ name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name ): with open('obj/' + name + '.pkl', 'rb') as f: return pickle.load(f) def main(): cnn = cnnMNIST() a = time.time() print('Retrieving data') cnn.get_data() b = time.time() print('Built the data in {} s'.format(b-a)) a = time.time() cnn.train() b = time.time() print('Training time: {} s'.format(b-a)) # cnn.test_eval() predictions, y = cnn.get_label_predictions() predictions_decode = predictions labels_decode = cnn.onenothot_labels(y) # np.save('{}_predictions.npy'.format(cnn.runname), predictions_decode) np.save('{}_ground_truth.npy'.format(cnn.runname), labels_decode) stop # Validation time validation_data = cnn.validation_batcher() answers = OrderedDict() for sample in validation_data: x = np.array(sample) predictions = cnn.sess.run( cnn.prediction, feed_dict = {cnn.x: x}) time_index = np.arange(predictions.shape[0]) mask = predictions >= 0.5 runname = sample.name.split('/')[-1] if np.sum(mask) != 0: counts = np.sum(np.squeeze(x[:, -1, :]), axis=-1) t = time_index[mask] t = [int(i) for i in t] index_guess = np.argmax(counts[t]) current_spectra = np.squeeze(x[t[index_guess], -1, :]) current_time = t[index_guess] + 15 answers[runname] = {'time': current_time, 'spectra': current_spectra} else: answers[runname] = {'time': 0, 'spectra': 0} save_obj(answers, '50knormalgru_hits') return main()
Vaidyanath/tempest
refs/heads/master
tempest/api/compute/images/__init__.py
12133432
astagi/taiga-back
refs/heads/master
taiga/locale/__init__.py
12133432
gnu-user/dtella
refs/heads/master
tests/test_common_ipv4.py
4
#!/usr/bin/env python # Tests for dtella/common/ipv4.py import fix_path import unittest from dtella.common.ipv4 import CidrNumToMask from dtella.common.ipv4 import CidrStringToIPMask from dtella.common.ipv4 import IsSubsetOf from dtella.common.ipv4 import MaskToCidrNum from dtella.common.ipv4 import SubnetMatcher class IPv4TestCase(unittest.TestCase): def testCidrNumToMask(self): self.assertRaises(ValueError, CidrNumToMask, -1) self.assertEqual(CidrNumToMask(0), 0) self.assertEqual(CidrNumToMask(16), (~0) << 16) self.assertEqual(CidrNumToMask(24), (~0) << 8) self.assertEqual(CidrNumToMask(32), ~0) self.assertRaises(ValueError, CidrNumToMask, 33) def testMaskToCidrNum(self): self.assertEqual(MaskToCidrNum(0), 0) self.assertEqual(MaskToCidrNum(~0 << 8), 24) self.assertEqual(MaskToCidrNum(~0 << 1), 31) self.assertEqual(MaskToCidrNum(~0), 32) self.assertRaises(ValueError, MaskToCidrNum, 12345) def testCidrStringToIPMask(self): self.assertEqual(CidrStringToIPMask("1.2.3.4/5"), (0x01020304, ~0<<(32-5))) self.assertEqual(CidrStringToIPMask("1.2.3.4"), (0x01020304, ~0)) self.assertRaises(ValueError, CidrStringToIPMask, "1.2.3.4//5") def testIsSubsetOf(self): C = CidrStringToIPMask self.assertTrue(IsSubsetOf(C("132.3.12.34"), C("132.3.0.0/0"))) self.assertTrue(IsSubsetOf(C("132.3.12.34"), C("132.3.0.0/16"))) self.assertTrue(IsSubsetOf(C("0.0.0.0/0"), C("0.0.0.0/0"))) self.assertTrue(IsSubsetOf(C("0.0.0.0/1"), C("0.0.0.0/0"))) self.assertFalse(IsSubsetOf(C("0.0.0.0/0"), C("0.0.0.0/1"))) self.assertFalse(IsSubsetOf(C("192.168.0.255"), C("192.168.1.0/24"))) self.assertTrue(IsSubsetOf(C("192.168.1.0"), C("192.168.1.0/24"))) self.assertTrue(IsSubsetOf(C("192.168.1.255"), C("192.168.1.0/24"))) self.assertFalse(IsSubsetOf(C("192.168.2.0"), C("192.168.1.0/24"))) self.assertTrue(IsSubsetOf(C("192.168.1.0/24"), C("192.168.0.0/16"))) self.assertFalse(IsSubsetOf(C("10.0.0.0/24"), C("192.168.0.0/16"))) def testSubnetMatcher(self): C = CidrStringToIPMask matcher = SubnetMatcher() self.assertFalse(matcher.containsRange(C("1.2.3.4"))) self.assertFalse(matcher.containsRange(C("132.3.0.0/0"))) matcher.addRange(C("132.3.0.0/0")) self.assertTrue(matcher.containsRange(C("0.0.0.0"))) self.assertTrue(matcher.containsRange(C("1.2.3.4"))) self.assertTrue(matcher.containsRange(C("132.3.12.34"))) self.assertTrue(matcher.containsRange(C("255.255.255.255"))) matcher.clear() matcher.addRange(C("128.210.0.0/15")) matcher.addRange(C("128.10.0.0/16")) matcher.addRange(C("1.0.0.0/8")) self.assertFalse(matcher.containsRange(C("0.0.0.0"))) self.assertTrue(matcher.containsRange(C("1.2.3.4"))) self.assertFalse(matcher.containsRange(C("128.209.255.255"))) self.assertTrue(matcher.containsRange(C("128.210.0.0"))) self.assertTrue(matcher.containsRange(C("128.211.123.1"))) self.assertTrue(matcher.containsRange(C("128.211.255.255"))) self.assertFalse(matcher.containsRange(C("128.212.0.0"))) self.assertFalse(matcher.containsRange(C("128.9.255.255"))) self.assertTrue(matcher.containsRange(C("128.10.0.0"))) self.assertTrue(matcher.containsRange(C("128.10.255.255"))) self.assertFalse(matcher.containsRange(C("128.11.0.0"))) self.assertFalse(matcher.containsRange(C("128.210.0.0/14"))) self.assertTrue(matcher.containsRange(C("128.210.0.0/16"))) self.assertTrue(matcher.containsRange(C("128.211.0.0/16"))) self.assertEqual(len(matcher.nets), 3) matcher.addRange(C("1.2.3.4/0")) matcher.addRange(C("1.2.3.4/5")) matcher.addRange(C("128.210.0.0/16")) self.assertEqual(len(matcher.nets), 1) self.assertTrue(matcher.containsRange(C("0.0.0.0/0"))) self.assertTrue(matcher.containsRange(C("0.0.0.0/1"))) self.assertTrue(matcher.containsRange(C("128.0.0.0/1"))) self.assertTrue(matcher.containsRange(C("0.0.0.0"))) self.assertTrue(matcher.containsRange(C("127.255.255.255"))) self.assertTrue(matcher.containsRange(C("128.0.0.0"))) self.assertTrue(matcher.containsRange(C("255.255.255.255"))) matcher.clear() matcher.addRange(C("0.0.0.0/1")) matcher.addRange(C("128.0.0.0/1")) self.assertTrue(matcher.containsRange(C("0.0.0.0"))) self.assertTrue(matcher.containsRange(C("127.255.255.255"))) self.assertTrue(matcher.containsRange(C("128.0.0.0"))) self.assertTrue(matcher.containsRange(C("255.255.255.255"))) self.assertTrue(matcher.containsRange(C("0.0.0.0/1"))) self.assertTrue(matcher.containsRange(C("128.0.0.0/1"))) # Does not support aggregation. self.assertFalse(matcher.containsRange(C("0.0.0.0/0"))) if __name__ == "__main__": unittest.main()
oduwa/Wheat-Count
refs/heads/master
PicNumero/spectral_roi.py
2
from skimage import data, io, segmentation, color from skimage.future import graph from matplotlib import pyplot as plt from scipy import misc from skimage.color import rgb2gray import numpy as np import Helper import Display def spectral_cluster(filename, compactness_val=30, n=6): ''' Apply spectral clustering to a given image using k-means clustering and display results. Args: filename: name of the image to segment. compactness_val: Controls the "boxyness" of each segment. Higher values mean a more boxed shape. n = number of clusters. ''' img = misc.imread(filename) labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n) out1 = color.label2rgb(labels1, img, kind='overlay', colors=['red','green','blue','cyan','magenta','yellow']) fig, ax = plt.subplots() ax.imshow(out1, interpolation='nearest') ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n)) plt.show() def experiment_with_parameters(): ''' Apply spectral clustering to test wheat image using k-means clustering with different values of k and different compactness values. Saves the results to the Clusters folder for inspection. ''' img = misc.imread("../Assets/wheat.png") compactness_values = [30, 50, 70, 100, 200, 300, 500, 700, 1000] n_segments_values = [3,4,5,6,7,8,9,10] for compactness_val in compactness_values: for n in n_segments_values: labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n) out1 = color.label2rgb(labels1, img, kind='overlay') fig, ax = plt.subplots() ax.imshow(out1, interpolation='nearest') ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n)) plt.savefig("../Clusters/c{}_k{}.png".format(compactness_val, n)) plt.close(fig) def extract_roi(img, labels_to_keep=[1,2]): ''' Given a wheat image, this method returns an image containing only the region of interest. Args: img: input image. labels_to_keep: cluster labels to be kept in image while pixels belonging to clusters besides these ones are removed. Return: roi_img: Input image containing only the region of interest. ''' label_img = segmentation.slic(img, compactness=30, n_segments=6) labels = np.unique(label_img);print(labels) gray = rgb2gray(img); for label in labels: if(label not in labels_to_keep): logicalIndex = (label_img == label) gray[logicalIndex] = 0; #Display.show_image(gray) return gray
Jeff-Wang93/vent
refs/heads/master
vent/core/file_drop/file_drop.py
1
import json import os import sys import time import uuid import pika from redis import Redis from redis import StrictRedis from rq import Queue from watchdog.events import PatternMatchingEventHandler from watchdog.observers import Observer class GZHandler(PatternMatchingEventHandler): """ Handles when an event on the directory being watched happens that matches the values in patterns """ patterns = ['*'] # want to ignore certain pcap files from splitter as they contain junk ignore_patterns = ['*-miscellaneous*'] # don't want to process files in on_modified for files that have already # been created and processed created_files = set() try: # let jobs run for up to one day q = Queue(connection=Redis(host='redis'), default_timeout=86400) r = StrictRedis(host='redis', port=6379, db=0) except Exception as e: # pragma: no cover print('Unable to connect to redis:', str(e)) def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ uid = str(uuid.uuid4()) hostname = os.environ.get('VENT_HOST') if not hostname: hostname = '' try: # TODO should directories be treated as bulk paths to send to a # plugin? if not event.is_directory: spath = event.src_path # wait for long copies to finish historicalSize = -1 while (historicalSize != os.path.getsize(spath)): historicalSize = os.path.getsize(spath) time.sleep(0.1) if os.path.getsize(spath) == 0: spath = str(spath) print('file drop ignoring empty file: {0}'.format(spath)) if spath.startswith('/files/trace_'): key = spath.split('_')[1] # Rabbit settings exchange = 'topic-poseidon-internal' exchange_type = 'topic' routing_key = 'poseidon.algos.decider' message = {} message[key] = {'valid': False, 'source': 'file_drop'} message = json.dumps(message) # Send Rabbit message try: connection = pika.BlockingConnection( pika.ConnectionParameters(host='rabbit') ) channel = connection.channel() channel.exchange_declare( exchange=exchange, exchange_type=exchange_type ) channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message) connection.close() except Exception as e: print('failed to send rabbit message because: ' + str(e)) return # check if the file was already queued and ignore exists = False print(uid + ' started ' + spath) jobs = self.r.keys(pattern='rq:job*') for job in jobs: print(uid + ' ***') description = self.r.hget( job, 'description').decode('utf-8') print(uid + ' ' + description) if description.startswith("watch.file_queue('"): print(uid + ' ' + description.split("watch.file_queue('" + hostname + '_')[1][:-2]) print(uid + ' ' + spath) if description.split("watch.file_queue('" + hostname + '_')[1][:-2] == spath: print(uid + ' true') exists = True elif description.startswith("watch.gpu_queue('"): print(uid + ' ' + description.split('"file": "')[1].split('"')[0]) print(uid + ' ' + spath) if description.split('"file": "')[1].split('"')[0] == spath: print(uid + ' true') exists = True print(uid + ' ***') if not exists: # !! TODO this should be a configuration option in the # vent.template print(uid + " let's queue it " + spath) # let jobs be queued for up to 30 days self.q.enqueue('watch.file_queue', hostname + '_' + spath, ttl=2592000) print(uid + ' end ' + spath) except Exception as e: # pragma: no cover print('file drop error: ' + str(e)) def on_created(self, event): self.created_files.add(event.src_path) self.process(event) def on_modified(self, event): # don't perform any action if file was already created or file is # deleted if (event.src_path not in self.created_files and os.path.exists(event.src_path)): # add to created files because the file was moved into directory, # which is what should be creating it, but some OS's treat it as a # modification with docker mounts self.created_files.add(event.src_path) self.process(event) if __name__ == '__main__': # pragma: no cover args = None if len(sys.argv) > 1: args = sys.argv[1:] observer = Observer() observer.schedule(GZHandler(), path=args[0] if args else '/files', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: # pragma: no cover observer.stop() observer.join()
fiddlerwoaroof/yinjar
refs/heads/master
main.py
1
import os.path import yaml import textwrap import math import libtcodpy as libtcod import glob libtcod.console_set_keyboard_repeat(500, 50) for fil in glob.glob('./data/namegen/*.cfg'): libtcod.namegen_parse(fil) help = ''' 'i': Inventory 'd': Drop 'g': Get item (Pick up) '?': Help Alt+Escape: Exit Arrow Keys for movement / selecting Name of item under the mouse shown above the health bar ''' from game import GameBase import levels import objects import utilities if __name__ == 'main': class Null: pass class SettingsObject(object): def __init__(self, setting_name, default=Null): self.setting_name = setting_name self.default = default def __get__(self, instance, owner): result = instance.settings.get(self.setting_name, self.default) if result is Null: raise KeyError('%s is not specified in the configuration' % self.setting_name) return result class Game(GameBase): #actual size of the window def load_settings(self): self.settings = yaml.safe_load( file(os.path.join('./data/main.yml')) ) if self.settings == None: self.settings = {} SCREEN_WIDTH = SettingsObject('screen_width', 80) SCREEN_HEIGHT = SettingsObject('screen_height', 50) PANEL_HEIGHT = 15 INVENTORY_WIDTH = 50 @property def MAP_WIDTH(self): return self.SCREEN_WIDTH @property def MAP_HEIGHT(self): return self.SCREEN_HEIGHT - (self.PANEL_HEIGHT + 2) BAR_WIDTH = 25 MSG_X = BAR_WIDTH + 2 MSG_HEIGHT = PANEL_HEIGHT @property def PANEL_Y(self): return self.SCREEN_HEIGHT - self.PANEL_HEIGHT @property def MSG_WIDTH(self): return self.SCREEN_WIDTH - self.MSG_X @property def MSG_HEIGHT(self): return self.PANEL_HEIGHT - 1 ROOM_MIN_SIZE = SettingsObject('room_min_wall_length', 4) ROOM_MAX_SIZE = SettingsObject('room_max_wall_length', 7) MAX_ROOMS = SettingsObject('max_number_rooms', 10) MAX_ROOM_MONSTERS = SettingsObject('max_number_room_monsters', 6) MAX_ROOM_ITEMS = SettingsObject('max_number_room_items', 3) CONFUSE_NUM_TURNS = 17 LIMIT_FPS = 20 #frames-per-second maximum def __init__(self): self.load_settings() GameBase.__init__(self, 'caer flinding', self.SCREEN_WIDTH, self.SCREEN_HEIGHT) self.select_cb = None self.panel = libtcod.console_new(self.SCREEN_WIDTH, self.PANEL_HEIGHT) self.levels = [] self.current_level = 0 self.levels = [levels.Level(self.MAP_WIDTH, self.MAP_HEIGHT, self.con, self.item_types, self.monster_types)] x,y = None,None self.player = objects.Player(self.level.map, self.con, x,y, '@', libtcod.white, fighter=objects.Fighter(hp=40, defense = 2, power = 11, death_function=self.player_death) ) def player_death(self, player): self.message('You died!', libtcod.red) self.game_state = 'dead' player.char = '%' player.color = libtcod.dark_red def setup_map(self): self.player.enter_level(self.level) self.level.setup(self.MAX_ROOMS, self.ROOM_MIN_SIZE, self.ROOM_MAX_SIZE, self.MAX_ROOM_MONSTERS, self.MAX_ROOM_ITEMS ) self.set_fov() def set_fov(self): self.player.enter_level(self.level) self.level.init_fov() self.level.recompute_fov(True) item_types = {} @classmethod def register_item_type(cls, chance): def _inner(typ): cls.item_types[typ] = chance return typ return _inner monster_types = {} @classmethod def register_monster_type(cls, typ, chance): cls.monster_types[typ] = chance return typ @property def level(self): return self.levels[self.current_level] @property def map(self): return self.level.map def change_level(self, down=True): change = 1 if down else -1 self.current_level += change if ( (self.current_level < 0 and not down) or (self.current_level >= len(self.levels)) ): new_level = levels.Level( self.MAP_WIDTH, self.MAP_HEIGHT, self.con, self.item_types, self.monster_types ) if down: self.levels.append(new_level) else: self.levels.insert(0,new_level) self.current_level = self.levels.index(new_level) self.setup_map() else: self.set_fov() def main(self): self.message('Welcome %s! Prepare to perish in the Tombs of the Ancient Kings.' % self.player.name, libtcod.red ) for x in GameBase.main(self): if x == 1: if ( self.game_state in ('playing','selecting') and self.player_action != 'didnt-take-turn' ): for object in self.level.objects: if object.ai: object.clear() object.ai.take_turn() for object in self.level.objects: object.clear() if self.game_state == 'selecting': self.cursor.clear() elif x == 2: if self.player_action == 'move': self.player.tick() def do_playing(self): if self.player_action != 'didnt-take-turn': for object in self.level.iter_objects(): if object.ai: object.clear() object.ai.take_turn() self.player.clear() if self.player_action == 'move': self.player.tick() def do_selecting(self): self.cursor.clear() def do_dead(self): pass mvkeyhandler = utilities.MovementKeyListener() @mvkeyhandler.up def mvkeyhandler(self): self.player.move_or_attack(0,-1) return 'move' @mvkeyhandler.down def mvkeyhandler(self): self.player.move_or_attack(0, 1) return 'move' @mvkeyhandler.left def mvkeyhandler(self): self.player.move_or_attack(-1, 0) return 'move' @mvkeyhandler.right def mvkeyhandler(self): self.player.move_or_attack(1, 0) return 'move' @mvkeyhandler.handle('i') def mvkeyhandler(self): item = self.inventory_menu('Choose item to use\n') if item is not None: item.bind_game(self) self.player.use(item) @mvkeyhandler.handle('d') def mvkeyhandler(self): chosen_item = self.inventory_menu('Choose item to drop\n') if chosen_item is not None: self.player.drop(chosen_item.owner) @mvkeyhandler.handle('n') def mvkeyhandler(self): chosen_item = self.inventory_menu('Choose item to unmod\n') if chosen_item is not None: data = chosen_item.mods.keys() index = self.menu('Choose \nmod to \nundo\n', data, self.INVENTORY_WIDTH) if index is not None: self.player.unmodify(chosen_item.name, data[index]) @mvkeyhandler.handle('m') def mvkeyhandler(self): chosen_item = self.inventory_menu('Choose item to mod\n') if chosen_item is not None: chosen_mod = self.mod_menu('Choose mod to apply\n') if chosen_mod is not None: self.player.modify(chosen_item.name, chosen_mod.name) @mvkeyhandler.handle('g') def mvkeyhandler(self): for obj in self.level.iter_objects(): if obj.x == self.player.x and obj.y == self.player.y and obj.item: self.player.pick_up(obj) @mvkeyhandler.handle('<') def mvkeyhandler(self): self.change_level(down=False) @mvkeyhandler.handle('>') def mvkeyhandler(self): self.change_level(down=True) @mvkeyhandler.handle('?') def mvkeyhandler(self): self.menu(help, [], 50) selectkeyhandler = utilities.MovementKeyListener() @selectkeyhandler.up def selectkeyhandler(self): self.cursor.y -= 1 @selectkeyhandler.down def selectkeyhandler(self): self.cursor.y += 1 @selectkeyhandler.left def selectkeyhandler(self): self.cursor.x -= 1 @selectkeyhandler.right def selectkeyhandler(self): self.cursor.x += 1 @selectkeyhandler.handle(libtcod.KEY_ENTER) def selectkeyhandler(self): self.select_cb(self.cursor.x, self.cursor.y) self.cursor.clear() self.game_state = 'playing' def render_all(self): for obj in self.level.iter_objects(): if obj != self.player: obj.draw(self.player) self.player.draw() if self.game_state == 'selecting': self.cursor.draw() if self.player.fov_recompute: self.level.recompute_fov() libtcod.console_blit(self.con, 0,0, self.SCREEN_WIDTH,self.SCREEN_HEIGHT, 0,0, 0) libtcod.console_set_default_background(self.panel, libtcod.black) libtcod.console_clear(self.panel) utilities.render_bar(self.panel, 1,1, self.BAR_WIDTH, 'HP', self.player.fighter.hp, self.player.fighter.max_hp, libtcod.red, libtcod.darker_red ) libtcod.console_print_ex(self.panel, self.BAR_WIDTH/2,3, libtcod.BKGND_NONE, libtcod.CENTER, '%s p %s d' %(self.player.fighter.power, self.player.fighter.defense) ) fps = libtcod.sys_get_fps() libtcod.console_print_ex(self.panel, self.BAR_WIDTH/2,4, libtcod.BKGND_NONE, libtcod.CENTER, '%s FPS' %(libtcod.sys_get_fps()) ) libtcod.console_set_default_foreground(self.panel, libtcod.light_gray) libtcod.console_print(self.panel, 1, 0, self.get_names_under_mouse()) y = 1 for line, color in self.game_msgs: libtcod.console_set_default_foreground(self.panel, color) libtcod.console_print_ex(self.panel, self.MSG_X, y, libtcod.BKGND_NONE, libtcod.LEFT, line) y += 1 libtcod.console_blit(self.panel, 0,0, self.SCREEN_WIDTH,self.PANEL_HEIGHT, 0,0, self.PANEL_Y) def main_menu(self): message = ( 'Welcome to YinJAR: is not Just Another Roguelike (WIP)', '', 'Choose an option:', '', ) options = ['Resume', 'Play', 'Exit'] result = self.menu('\n'.join(message), options, len(message[0])) if result is not None: return options[result] game_instance = Game() from monsters import MonsterLoader if __name__ == '__main__': from main import game_instance from items import * from utilities import * from maps import * from objects import * from monsters import * from functools import partial render_bar = partial(render_bar, game_instance.panel) ml = MonsterLoader(os.path.join('.','data','monsters')) ml.load_monsters() il = ItemLoader(os.path.join('.','data','items')) il.load_items() game_instance.load_settings() action = game_instance.main_menu() libtcod.sys_set_fps(Game.LIMIT_FPS) while action is None or action.lower() != 'exit': if action is not None: if action.lower() == 'play': game_instance.setup_map() if action.lower() in {'play', 'resume'}: game_instance.main() libtcod.console_clear(0) action = game_instance.main_menu()
alvaroaleman/ansible
refs/heads/devel
lib/ansible/modules/cloud/misc/virt_net.py
23
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Maciej Delmanowski <drybjed@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: virt_net author: "Maciej Delmanowski (@drybjed)" version_added: "2.0" short_description: Manage libvirt network configuration description: - Manage I(libvirt) networks. options: name: required: true aliases: ['network'] description: - name of the network being managed. Note that network must be previously defined with xml. state: required: false choices: [ "active", "inactive", "present", "absent" ] description: - specify which state you want a network to be in. If 'active', network will be started. If 'present', ensure that network is present but do not change its state; if it's missing, you need to specify xml argument. If 'inactive', network will be stopped. If 'undefined' or 'absent', network will be removed from I(libvirt) configuration. command: required: false choices: [ "define", "create", "start", "stop", "destroy", "undefine", "get_xml", "list_nets", "facts", "info", "status", "modify"] description: - in addition to state management, various non-idempotent commands are available. See examples. Modify was added in version 2.1 autostart: required: false choices: ["yes", "no"] description: - Specify if a given storage pool should be started automatically on system boot. uri: required: false default: "qemu:///system" description: - libvirt connection uri. xml: required: false description: - XML document used with the define command. requirements: - "python >= 2.6" - "python-libvirt" - "python-lxml" ''' EXAMPLES = ''' # Define a new network - virt_net: command: define name: br_nat xml: '{{ lookup("template", "network/bridge.xml.j2") }}' # Start a network - virt_net: command: create name: br_nat # List available networks - virt_net: command: list_nets # Get XML data of a specified network - virt_net: command: get_xml name: br_nat # Stop a network - virt_net: command: destroy name: br_nat # Undefine a network - virt_net: command: undefine name: br_nat # Gather facts about networks # Facts will be available as 'ansible_libvirt_networks' - virt_net: command: facts # Gather information about network managed by 'libvirt' remotely using uri - virt_net: command: info uri: '{{ item }}' with_items: '{{ libvirt_uris }}' register: networks # Ensure that a network is active (needs to be defined and built first) - virt_net: state: active name: br_nat # Ensure that a network is inactive - virt_net: state: inactive name: br_nat # Ensure that a given network will be started at boot - virt_net: autostart: yes name: br_nat # Disable autostart for a given network - virt_net: autostart: no name: br_nat ''' VIRT_FAILED = 1 VIRT_SUCCESS = 0 VIRT_UNAVAILABLE=2 try: import libvirt except ImportError: HAS_VIRT = False else: HAS_VIRT = True try: from lxml import etree except ImportError: HAS_XML = False else: HAS_XML = True from ansible.module_utils.basic import AnsibleModule ALL_COMMANDS = [] ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', 'undefine', 'destroy', 'get_xml', 'define', 'modify' ] HOST_COMMANDS = [ 'list_nets', 'facts', 'info' ] ALL_COMMANDS.extend(ENTRY_COMMANDS) ALL_COMMANDS.extend(HOST_COMMANDS) ENTRY_STATE_ACTIVE_MAP = { 0 : "inactive", 1 : "active" } ENTRY_STATE_AUTOSTART_MAP = { 0 : "no", 1 : "yes" } ENTRY_STATE_PERSISTENT_MAP = { 0 : "no", 1 : "yes" } class EntryNotFound(Exception): pass class LibvirtConnection(object): def __init__(self, uri, module): self.module = module conn = libvirt.open(uri) if not conn: raise Exception("hypervisor connection failure") self.conn = conn def find_entry(self, entryid): # entryid = -1 returns a list of everything results = [] # Get active entries for name in self.conn.listNetworks(): entry = self.conn.networkLookupByName(name) results.append(entry) # Get inactive entries for name in self.conn.listDefinedNetworks(): entry = self.conn.networkLookupByName(name) results.append(entry) if entryid == -1: return results for entry in results: if entry.name() == entryid: return entry raise EntryNotFound("network %s not found" % entryid) def create(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).create() else: try: state = self.find_entry(entryid).isActive() except: return self.module.exit_json(changed=True) if not state: return self.module.exit_json(changed=True) def modify(self, entryid, xml): network = self.find_entry(entryid) # identify what type of entry is given in the xml new_data = etree.fromstring(xml) old_data = etree.fromstring(network.XMLDesc(0)) if new_data.tag == 'host': mac_addr = new_data.get('mac') hosts = old_data.xpath('/network/ip/dhcp/host') # find the one mac we're looking for host = None for h in hosts: if h.get('mac') == mac_addr: host = h break if host is None: # add the host if not self.module.check_mode: res = network.update (libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_LAST, libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST, -1, xml, libvirt.VIR_NETWORK_UPDATE_AFFECT_CURRENT) else: # pretend there was a change res = 0 if res == 0: return True else: # change the host if host.get('name') == new_data.get('name') and host.get('ip') == new_data.get('ip'): return False else: if not self.module.check_mode: res = network.update (libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY, libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST, -1, xml, libvirt.VIR_NETWORK_UPDATE_AFFECT_CURRENT) else: # pretend there was a change res = 0 if res == 0: return True # command, section, parentIndex, xml, flags=0 self.module.fail_json(msg='updating this is not supported yet '+unicode(xml)) def destroy(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).destroy() else: if self.find_entry(entryid).isActive(): return self.module.exit_json(changed=True) def undefine(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).undefine() else: if not self.find_entry(entryid): return self.module.exit_json(changed=True) def get_status2(self, entry): state = entry.isActive() return ENTRY_STATE_ACTIVE_MAP.get(state,"unknown") def get_status(self, entryid): if not self.module.check_mode: state = self.find_entry(entryid).isActive() return ENTRY_STATE_ACTIVE_MAP.get(state,"unknown") else: try: state = self.find_entry(entryid).isActive() return ENTRY_STATE_ACTIVE_MAP.get(state,"unknown") except: return ENTRY_STATE_ACTIVE_MAP.get("inactive","unknown") def get_uuid(self, entryid): return self.find_entry(entryid).UUIDString() def get_xml(self, entryid): return self.find_entry(entryid).XMLDesc(0) def get_forward(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) try: result = xml.xpath('/network/forward')[0].get('mode') except: raise ValueError('Forward mode not specified') return result def get_domain(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) try: result = xml.xpath('/network/domain')[0].get('name') except: raise ValueError('Domain not specified') return result def get_macaddress(self, entryid): xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0)) try: result = xml.xpath('/network/mac')[0].get('address') except: raise ValueError('MAC address not specified') return result def get_autostart(self, entryid): state = self.find_entry(entryid).autostart() return ENTRY_STATE_AUTOSTART_MAP.get(state,"unknown") def get_autostart2(self, entryid): if not self.module.check_mode: return self.find_entry(entryid).autostart() else: try: return self.find_entry(entryid).autostart() except: return self.module.exit_json(changed=True) def set_autostart(self, entryid, val): if not self.module.check_mode: return self.find_entry(entryid).setAutostart(val) else: try: state = self.find_entry(entryid).autostart() except: return self.module.exit_json(changed=True) if bool(state) != val: return self.module.exit_json(changed=True) def get_bridge(self, entryid): return self.find_entry(entryid).bridgeName() def get_persistent(self, entryid): state = self.find_entry(entryid).isPersistent() return ENTRY_STATE_PERSISTENT_MAP.get(state,"unknown") def define_from_xml(self, entryid, xml): if not self.module.check_mode: return self.conn.networkDefineXML(xml) else: try: self.find_entry(entryid) except: return self.module.exit_json(changed=True) class VirtNetwork(object): def __init__(self, uri, module): self.module = module self.uri = uri self.conn = LibvirtConnection(self.uri, self.module) def get_net(self, entryid): return self.conn.find_entry(entryid) def list_nets(self, state=None): results = [] for entry in self.conn.find_entry(-1): if state: if state == self.conn.get_status2(entry): results.append(entry.name()) else: results.append(entry.name()) return results def state(self): results = [] for entry in self.list_nets(): state_blurb = self.conn.get_status(entry) results.append("%s %s" % (entry,state_blurb)) return results def autostart(self, entryid): return self.conn.set_autostart(entryid, True) def get_autostart(self, entryid): return self.conn.get_autostart2(entryid) def set_autostart(self, entryid, state): return self.conn.set_autostart(entryid, state) def create(self, entryid): return self.conn.create(entryid) def modify(self, entryid, xml): return self.conn.modify(entryid, xml) def start(self, entryid): return self.conn.create(entryid) def stop(self, entryid): return self.conn.destroy(entryid) def destroy(self, entryid): return self.conn.destroy(entryid) def undefine(self, entryid): return self.conn.undefine(entryid) def status(self, entryid): return self.conn.get_status(entryid) def get_xml(self, entryid): return self.conn.get_xml(entryid) def define(self, entryid, xml): return self.conn.define_from_xml(entryid, xml) def info(self): return self.facts(facts_mode='info') def facts(self, facts_mode='facts'): results = dict() for entry in self.list_nets(): results[entry] = dict() results[entry]["autostart"] = self.conn.get_autostart(entry) results[entry]["persistent"] = self.conn.get_persistent(entry) results[entry]["state"] = self.conn.get_status(entry) results[entry]["bridge"] = self.conn.get_bridge(entry) results[entry]["uuid"] = self.conn.get_uuid(entry) try: results[entry]["forward_mode"] = self.conn.get_forward(entry) except ValueError: pass try: results[entry]["domain"] = self.conn.get_domain(entry) except ValueError: pass try: results[entry]["macaddress"] = self.conn.get_macaddress(entry) except ValueError: pass facts = dict() if facts_mode == 'facts': facts["ansible_facts"] = dict() facts["ansible_facts"]["ansible_libvirt_networks"] = results elif facts_mode == 'info': facts['networks'] = results return facts def core(module): state = module.params.get('state', None) name = module.params.get('name', None) command = module.params.get('command', None) uri = module.params.get('uri', None) xml = module.params.get('xml', None) autostart = module.params.get('autostart', None) v = VirtNetwork(uri, module) res = {} if state and command == 'list_nets': res = v.list_nets(state=state) if not isinstance(res, dict): res = { command: res } return VIRT_SUCCESS, res if state: if not name: module.fail_json(msg = "state change requires a specified name") res['changed'] = False if state in [ 'active' ]: if v.status(name) is not 'active': res['changed'] = True res['msg'] = v.start(name) elif state in [ 'present' ]: try: v.get_net(name) except EntryNotFound: if not xml: module.fail_json(msg = "network '" + name + "' not present, but xml not specified") v.define(name, xml) res = {'changed': True, 'created': name} elif state in [ 'inactive' ]: entries = v.list_nets() if name in entries: if v.status(name) is not 'inactive': res['changed'] = True res['msg'] = v.destroy(name) elif state in [ 'undefined', 'absent' ]: entries = v.list_nets() if name in entries: if v.status(name) is not 'inactive': v.destroy(name) res['changed'] = True res['msg'] = v.undefine(name) else: module.fail_json(msg="unexpected state") return VIRT_SUCCESS, res if command: if command in ENTRY_COMMANDS: if not name: module.fail_json(msg = "%s requires 1 argument: name" % command) if command in ('define', 'modify'): if not xml: module.fail_json(msg = command+" requires xml argument") try: v.get_net(name) except EntryNotFound: v.define(name, xml) res = {'changed': True, 'created': name} else: if command == 'modify': mod = v.modify(name, xml) res = {'changed': mod, 'modified': name} return VIRT_SUCCESS, res res = getattr(v, command)(name) if not isinstance(res, dict): res = { command: res } return VIRT_SUCCESS, res elif hasattr(v, command): res = getattr(v, command)() if not isinstance(res, dict): res = { command: res } return VIRT_SUCCESS, res else: module.fail_json(msg="Command %s not recognized" % command) if autostart is not None: if not name: module.fail_json(msg = "state change requires a specified name") res['changed'] = False if autostart: if not v.get_autostart(name): res['changed'] = True res['msg'] = v.set_autostart(name, True) else: if v.get_autostart(name): res['changed'] = True res['msg'] = v.set_autostart(name, False) return VIRT_SUCCESS, res module.fail_json(msg="expected state or command parameter to be specified") def main(): module = AnsibleModule ( argument_spec = dict( name = dict(aliases=['network']), state = dict(choices=['active', 'inactive', 'present', 'absent']), command = dict(choices=ALL_COMMANDS), uri = dict(default='qemu:///system'), xml = dict(), autostart = dict(type='bool') ), supports_check_mode = True ) if not HAS_VIRT: module.fail_json( msg='The `libvirt` module is not importable. Check the requirements.' ) if not HAS_XML: module.fail_json( msg='The `lxml` module is not importable. Check the requirements.' ) rc = VIRT_SUCCESS try: rc, result = core(module) except Exception as e: module.fail_json(msg=str(e)) if rc != 0: # something went wrong emit the msg module.fail_json(rc=rc, msg=result) else: module.exit_json(**result) if __name__ == '__main__': main()
tedi3231/openerp
refs/heads/master
build/lib/openerp/addons/point_of_sale/wizard/pos_box.py
5
#!/usr/bin/env python from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp.addons.account.wizard.pos_box import CashBox class PosBox(CashBox): _register = False def run(self, cr, uid, ids, context=None): if not context: context = dict() active_model = context.get('active_model', False) or False active_ids = context.get('active_ids', []) or [] if active_model == 'pos.session': records = self.pool.get(active_model).browse(cr, uid, active_ids, context=context) bank_statements = [record.cash_register_id for record in records if record.cash_register_id] if not bank_statements: raise osv.except_osv(_('Error!'), _("There is no cash register for this PoS Session")) return self._run(cr, uid, ids, bank_statements, context=context) else: return super(PosBox, self).run(cr, uid, ids, context=context) class PosBoxIn(PosBox): _inherit = 'cash.box.in' def _compute_values_for_statement_line(self, cr, uid, box, record, context=None): values = super(PosBoxIn, self)._compute_values_for_statement_line(cr, uid, box, record, context=context) active_model = context.get('active_model', False) or False active_ids = context.get('active_ids', []) or [] if active_model == 'pos.session': session = self.pool.get(active_model).browse(cr, uid, active_ids, context=context)[0] values['ref'] = session.name return values class PosBoxOut(PosBox): _inherit = 'cash.box.out' def _compute_values_for_statement_line(self, cr, uid, box, record, context=None): values = super(PosBoxOut, self)._compute_values_for_statement_line(cr, uid, box, record, context=context) active_model = context.get('active_model', False) or False active_ids = context.get('active_ids', []) or [] if active_model == 'pos.session': session = self.pool.get(active_model).browse(cr, uid, active_ids, context=context)[0] values['ref'] = session.name return values
r0h4n/commons
refs/heads/master
tendrl/commons/flows/authorize_ssh_key/__init__.py
3
from tendrl.commons import flows from tendrl.commons.flows.exceptions import FlowExecutionFailedError from tendrl.commons.utils.ssh import authorize_key class AuthorizeSshKey(flows.BaseFlow): internal = True def __init__(self, *args, **kwargs): self._defs = { "help": "Authorize SSH Key", "uuid": "759e639a-1315-11e7-93ae-92361f002671" } super(AuthorizeSshKey, self).__init__(*args, **kwargs) def run(self): ssh_key = self.parameters['ssh_key'] ret_val, err = authorize_key.AuthorizeKey(ssh_key).run() if ret_val is not True or err != "": raise FlowExecutionFailedError(err) return True
jdreaver/vispy
refs/heads/master
vispy/gloo/tests/test_globject.py
19
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier. All rights reserved. # Distributed under the terms of the new BSD License. # ----------------------------------------------------------------------------- from vispy.testing import run_tests_if_main from vispy.gloo.globject import GLObject def test_globject(): """ Test gl object uinique id and GLIR CREATE command """ objects = [GLObject() for i in range(10)] ids = [ob.id for ob in objects] # Verify that each id is unique (test should not care how) assert len(set(ids)) == len(objects) # Verify that glir commands have been created commands = [] for ob in objects: commands.extend(ob._glir.clear()) assert len(commands) == len(objects) for cmd in commands: assert cmd[0] == 'CREATE' # Delete ob = objects[-1] q = ob._glir # get it now, because its gone after we delete it ob.delete() cmd = q.clear()[-1] assert cmd[0] == 'DELETE' run_tests_if_main()
groove-x/gxredis
refs/heads/master
gxredis/dao.py
1
from .pubsub import RedisChannel from .types import RedisType class RedisDao(object): """ base class for Redis DAO """ def __init__(self, redis_client, key_params=None): self._key_params = key_params or {} self._redis_client = redis_client self._set_instance_attributes() def __repr__(self): return '{}(key_params={})'.format( self.__class__.__name__, self._key_params) def pipeline(self): """ create a Redis pipeline """ pipeline = self._redis_client.pipeline() members = {key: val.clone(redis_client=pipeline) for key, val in self._members.items()} return RedisPipeline(pipeline, members) def _set_instance_attributes(self): """ set instance attributes using class attributes """ members = {} definitions = self._gather_definitions() for key, def_ in definitions.items(): member = def_.clone( redis_client=self._redis_client, key_params=self._key_params) setattr(self, key, member) members[key] = member self._members = members def _gather_definitions(self): """ gather RedisType definitions """ definitions = {} for attr_name in dir(self): attr = getattr(self, attr_name) if isinstance(attr, (RedisType, RedisChannel)): definitions[attr_name] = attr return definitions class RedisPipeline(object): """ Redis pipeline """ def __init__(self, pipeline, members): self._pipeline = pipeline self._set_members(members) def __repr__(self): return '{}'.format(self.__class__.__name__) def _set_members(self, members): self._members = members for key, val in members.items(): setattr(self, key, val) def execute(self): self._pipeline.execute()