\n\n'''\n namespace = 'urn:oasis:names:tc:xliff:document:1.1'\n unversioned_namespace = 'urn:oasis:names:tc:xliff:document:'\n\n suggestions_in_format = True\n \"\"\"xliff units have alttrans tags which can be used to store suggestions\"\"\"\n\n def __init__(self, *args, **kwargs):\n self._filename = None\n lisa.LISAfile.__init__(self, *args, **kwargs)\n self._messagenum = 0\n\n def initbody(self):\n # detect the xliff namespace, handle both 1.1 and 1.2\n for prefix, ns in self.document.getroot().nsmap.items():\n if ns and ns.startswith(self.unversioned_namespace):\n self.namespace = ns\n break\n else:\n # handle crappy xliff docs without proper namespace declaration\n # by simply using the xmlns default namespace\n self.namespace = self.document.getroot().nsmap.get(None, None)\n\n if self._filename:\n filenode = self.getfilenode(self._filename, createifmissing=True)\n else:\n filenode = self.document.getroot().iterchildren(self.namespaced('file')).next()\n self.body = self.getbodynode(filenode, createifmissing=True)\n\n def addheader(self):\n \"\"\"Initialise the file header.\"\"\"\n pass\n\n def createfilenode(self, filename, sourcelanguage=None,\n targetlanguage=None, datatype='plaintext'):\n \"\"\"creates a filenode with the given filename. All parameters\n are needed for XLIFF compliance.\"\"\"\n if sourcelanguage is None:\n sourcelanguage = self.sourcelanguage\n if targetlanguage is None:\n targetlanguage = self.targetlanguage\n\n # find the default NoName file tag and use it instead of creating a new one\n for filenode in self.document.getroot().iterchildren(self.namespaced(\"file\")):\n if filenode.get(\"original\") == \"NoName\":\n filenode.set(\"original\", filename)\n filenode.set(\"source-language\", sourcelanguage)\n if targetlanguage:\n filenode.set(\"target-language\", targetlanguage)\n return filenode\n\n filenode = etree.Element(self.namespaced(\"file\"))\n filenode.set(\"original\", filename)\n filenode.set(\"source-language\", sourcelanguage)\n if targetlanguage:\n filenode.set(\"target-language\", targetlanguage)\n filenode.set(\"datatype\", datatype)\n bodyNode = etree.SubElement(filenode, self.namespaced(self.bodyNode))\n return filenode\n\n def getfilename(self, filenode):\n \"\"\"returns the name of the given file\"\"\"\n return filenode.get(\"original\")\n\n def setfilename(self, filenode, filename):\n \"\"\"set the name of the given file\"\"\"\n return filenode.set(\"original\", filename)\n\n def getfilenames(self):\n \"\"\"returns all filenames in this XLIFF file\"\"\"\n filenodes = self.document.getroot().iterchildren(self.namespaced(\"file\"))\n filenames = [self.getfilename(filenode) for filenode in filenodes]\n filenames = filter(None, filenames)\n if len(filenames) == 1 and filenames[0] == '':\n filenames = []\n return filenames\n\n def getfilenode(self, filename, createifmissing=False):\n \"\"\"finds the filenode with the given name\"\"\"\n filenodes = self.document.getroot().iterchildren(self.namespaced(\"file\"))\n for filenode in filenodes:\n if self.getfilename(filenode) == filename:\n return filenode\n if createifmissing:\n filenode = self.createfilenode(filename)\n return filenode\n return None\n\n def getids(self, filename=None):\n if not filename:\n return super(xlifffile, self).getids()\n\n self.id_index = {}\n prefix = filename + ID_SEPARATOR\n units = (unit for unit in self.units if unit.getid().startswith(prefix))\n for index, unit in enumerate(units):\n self.id_index[unit.getid()[len(prefix):]] = unit\n return self.id_index.keys()\n\n def setsourcelanguage(self, language):\n if not language:\n return\n filenode = self.document.getroot().iterchildren(self.namespaced('file')).next()\n filenode.set(\"source-language\", language)\n\n def getsourcelanguage(self):\n filenode = self.document.getroot().iterchildren(self.namespaced('file')).next()\n return filenode.get(\"source-language\")\n sourcelanguage = property(getsourcelanguage, setsourcelanguage)\n\n def settargetlanguage(self, language):\n if not language:\n return\n filenode = self.document.getroot().iterchildren(self.namespaced('file')).next()\n filenode.set(\"target-language\", language)\n\n def gettargetlanguage(self):\n filenode = self.document.getroot().iterchildren(self.namespaced('file')).next()\n return filenode.get(\"target-language\")\n targetlanguage = property(gettargetlanguage, settargetlanguage)\n\n def getdatatype(self, filename=None):\n \"\"\"Returns the datatype of the stored file. If no filename is given,\n the datatype of the first file is given.\"\"\"\n if filename:\n node = self.getfilenode(filename)\n if not node is None:\n return node.get(\"datatype\")\n else:\n filenames = self.getfilenames()\n if len(filenames) > 0 and filenames[0] != \"NoName\":\n return self.getdatatype(filenames[0])\n return \"\"\n\n def getdate(self, filename=None):\n \"\"\"Returns the date attribute for the file.\n\n If no filename is given, the date of the first file is given.\n If the date attribute is not specified, None is returned.\n\n :returns: Date attribute of file\n :rtype: Date or None\n \"\"\"\n if filename:\n node = self.getfilenode(filename)\n if not node is None:\n return node.get(\"date\")\n else:\n filenames = self.getfilenames()\n if len(filenames) > 0 and filenames[0] != \"NoName\":\n return self.getdate(filenames[0])\n return None\n\n def removedefaultfile(self):\n \"\"\"We want to remove the default file-tag as soon as possible if we\n know if still present and empty.\"\"\"\n filenodes = list(self.document.getroot().iterchildren(self.namespaced(\"file\")))\n if len(filenodes) > 1:\n for filenode in filenodes:\n if (filenode.get(\"original\") == \"NoName\" and\n not list(filenode.iterdescendants(self.namespaced(self.UnitClass.rootNode)))):\n self.document.getroot().remove(filenode)\n break\n\n def getheadernode(self, filenode, createifmissing=False):\n \"\"\"finds the header node for the given filenode\"\"\"\n # TODO: Deprecated?\n headernode = filenode.iterchildren(self.namespaced(\"header\"))\n try:\n return headernode.next()\n except StopIteration:\n pass\n if not createifmissing:\n return None\n headernode = etree.SubElement(filenode, self.namespaced(\"header\"))\n return headernode\n\n def getbodynode(self, filenode, createifmissing=False):\n \"\"\"finds the body node for the given filenode\"\"\"\n bodynode = filenode.iterchildren(self.namespaced(\"body\"))\n try:\n return bodynode.next()\n except StopIteration:\n pass\n if not createifmissing:\n return None\n bodynode = etree.SubElement(filenode, self.namespaced(\"body\"))\n return bodynode\n\n def addsourceunit(self, source, filename=\"NoName\", createifmissing=False):\n \"\"\"adds the given trans-unit to the last used body node if the\n filename has changed it uses the slow method instead (will\n create the nodes required if asked). Returns success\"\"\"\n if self._filename != filename:\n if not self.switchfile(filename, createifmissing):\n return None\n unit = super(xlifffile, self).addsourceunit(source)\n self._messagenum += 1\n unit.setid(\"%d\" % self._messagenum)\n return unit\n\n def switchfile(self, filename, createifmissing=False):\n \"\"\"Adds the given trans-unit (will create the nodes required if asked).\n\n :returns: Success\n :rtype: Boolean\n \"\"\"\n self._filename = filename\n filenode = self.getfilenode(filename)\n if filenode is None:\n if not createifmissing:\n return False\n filenode = self.createfilenode(filename)\n self.document.getroot().append(filenode)\n\n self.body = self.getbodynode(filenode, createifmissing=createifmissing)\n if self.body is None:\n return False\n self._messagenum = len(list(self.body.iterdescendants(self.namespaced(\"trans-unit\"))))\n # TODO: was 0 based before - consider\n # messagenum = len(self.units)\n # TODO: we want to number them consecutively inside a body/file tag\n # instead of globally in the whole XLIFF file, but using\n # len(self.units) will be much faster\n return True\n\n def creategroup(self, filename=\"NoName\", createifmissing=False, restype=None):\n \"\"\"adds a group tag into the specified file\"\"\"\n if self._filename != filename:\n if not self.switchfile(filename, createifmissing):\n return None\n group = etree.SubElement(self.body, self.namespaced(\"group\"))\n if restype:\n group.set(\"restype\", restype)\n return group\n\n def __str__(self):\n self.removedefaultfile()\n return super(xlifffile, self).__str__()\n\n @classmethod\n def parsestring(cls, storestring):\n \"\"\"Parses the string to return the correct file object\"\"\"\n xliff = super(xlifffile, cls).parsestring(storestring)\n if xliff.units:\n header = xliff.units[0]\n if ((\"gettext-domain-header\" in (header.getrestype() or \"\") or\n xliff.getdatatype() == \"po\") and\n cls.__name__.lower() != \"poxlifffile\"):\n from translate.storage import poxliff\n xliff = poxliff.PoXliffFile.parsestring(storestring)\n return xliff\n"},"license":{"kind":"string","value":"mpl-2.0"}}},{"rowIdx":476120,"cells":{"repo_name":{"kind":"string","value":"amanuel/bigcouch"},"path":{"kind":"string","value":"couchjs/scons/scons-local-2.0.1/SCons/Tool/packaging/tarbz2.py"},"copies":{"kind":"string","value":"61"},"size":{"kind":"string","value":"1803"},"content":{"kind":"string","value":"\"\"\"SCons.Tool.Packaging.tarbz2\n\nThe tarbz2 SRC packager.\n\"\"\"\n\n#\n# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation\n# \n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n__revision__ = \"src/engine/SCons/Tool/packaging/tarbz2.py 5134 2010/08/16 23:02:40 bdeegan\"\n\nfrom SCons.Tool.packaging import stripinstallbuilder, putintopackageroot\n\ndef package(env, target, source, PACKAGEROOT, **kw):\n bld = env['BUILDERS']['Tar']\n bld.set_suffix('.tar.gz')\n target, source = putintopackageroot(target, source, env, PACKAGEROOT)\n target, source = stripinstallbuilder(target, source, env)\n return bld(env, target, source, TARFLAGS='-jc')\n\n# Local Variables:\n# tab-width:4\n# indent-tabs-mode:nil\n# End:\n# vim: set expandtab tabstop=4 shiftwidth=4:\n"},"license":{"kind":"string","value":"apache-2.0"}}},{"rowIdx":476121,"cells":{"repo_name":{"kind":"string","value":"NeCTAR-RC/nova"},"path":{"kind":"string","value":"nova/tests/unit/virt/libvirt/test_imagecache.py"},"copies":{"kind":"string","value":"7"},"size":{"kind":"string","value":"42584"},"content":{"kind":"string","value":"# Copyright 2012 Michael Still and Canonical Inc\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport contextlib\nimport hashlib\nimport os\nimport time\n\nimport mock\nfrom oslo_concurrency import lockutils\nfrom oslo_concurrency import processutils\nfrom oslo_config import cfg\nfrom oslo_log import formatters\nfrom oslo_log import log as logging\nfrom oslo_serialization import jsonutils\nfrom oslo_utils import importutils\nfrom six.moves import cStringIO\n\nfrom nova import conductor\nfrom nova import context\nfrom nova import objects\nfrom nova import test\nfrom nova.tests.unit import fake_instance\nfrom nova import utils\nfrom nova.virt.libvirt import imagecache\nfrom nova.virt.libvirt import utils as libvirt_utils\n\nCONF = cfg.CONF\nCONF.import_opt('compute_manager', 'nova.service')\nCONF.import_opt('host', 'nova.netconf')\n\n\n@contextlib.contextmanager\ndef intercept_log_messages():\n try:\n mylog = logging.getLogger('nova')\n stream = cStringIO()\n handler = logging.logging.StreamHandler(stream)\n handler.setFormatter(formatters.ContextFormatter())\n mylog.logger.addHandler(handler)\n yield stream\n finally:\n mylog.logger.removeHandler(handler)\n\n\nclass ImageCacheManagerTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super(ImageCacheManagerTestCase, self).setUp()\n self.stock_instance_names = set(['instance-00000001',\n 'instance-00000002',\n 'instance-00000003',\n 'banana-42-hamster'])\n\n def test_read_stored_checksum_missing(self):\n self.stub_out('os.path.exists', lambda x: False)\n csum = imagecache.read_stored_checksum('/tmp/foo', timestamped=False)\n self.assertIsNone(csum)\n\n @mock.patch.object(os.path, 'exists', return_value=True)\n @mock.patch.object(time, 'time', return_value=2000000)\n @mock.patch.object(os.path, 'getmtime', return_value=1000000)\n def test_get_age_of_file(self, mock_getmtime, mock_time, mock_exists):\n image_cache_manager = imagecache.ImageCacheManager()\n exists, age = image_cache_manager._get_age_of_file('/tmp')\n self.assertTrue(exists)\n self.assertEqual(1000000, age)\n\n @mock.patch.object(os.path, 'exists', return_value=False)\n def test_get_age_of_file_not_exists(self, mock_exists):\n image_cache_manager = imagecache.ImageCacheManager()\n exists, age = image_cache_manager._get_age_of_file('/tmp')\n self.assertFalse(exists)\n self.assertEqual(0, age)\n\n def test_read_stored_checksum(self):\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n\n csum_input = '{\"sha1\": \"fdghkfhkgjjksfdgjksjkghsdf\"}\\n'\n fname = os.path.join(tmpdir, 'aaa')\n info_fname = imagecache.get_info_filename(fname)\n f = open(info_fname, 'w')\n f.write(csum_input)\n f.close()\n\n csum_output = imagecache.read_stored_checksum(fname,\n timestamped=False)\n self.assertEqual(csum_input.rstrip(),\n '{\"sha1\": \"%s\"}' % csum_output)\n\n def test_read_stored_checksum_legacy_essex(self):\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n\n fname = os.path.join(tmpdir, 'aaa')\n old_fname = fname + '.sha1'\n f = open(old_fname, 'w')\n f.write('fdghkfhkgjjksfdgjksjkghsdf')\n f.close()\n\n csum_output = imagecache.read_stored_checksum(fname,\n timestamped=False)\n self.assertEqual(csum_output, 'fdghkfhkgjjksfdgjksjkghsdf')\n self.assertFalse(os.path.exists(old_fname))\n info_fname = imagecache.get_info_filename(fname)\n self.assertTrue(os.path.exists(info_fname))\n\n def test_list_base_images(self):\n listing = ['00000001',\n 'ephemeral_0_20_None',\n '17d1b00b81642842e514494a78e804e9a511637c_5368709120.info',\n '00000004',\n 'swap_1000']\n images = ['e97222e91fc4241f49a7f520d1dcf446751129b3_sm',\n 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm',\n 'e97222e91fc4241f49a7f520d1dcf446751129b3',\n '17d1b00b81642842e514494a78e804e9a511637c',\n '17d1b00b81642842e514494a78e804e9a511637c_5368709120',\n '17d1b00b81642842e514494a78e804e9a511637c_10737418240']\n listing.extend(images)\n\n self.stub_out('os.listdir', lambda x: listing)\n self.stub_out('os.path.isfile', lambda x: True)\n\n base_dir = '/var/lib/nova/instances/_base'\n self.flags(instances_path='/var/lib/nova/instances')\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._list_base_images(base_dir)\n\n sanitized = []\n for ent in image_cache_manager.unexplained_images:\n sanitized.append(ent.replace(base_dir + '/', ''))\n\n self.assertEqual(sorted(sanitized), sorted(images))\n\n expected = os.path.join(base_dir,\n 'e97222e91fc4241f49a7f520d1dcf446751129b3')\n self.assertIn(expected, image_cache_manager.unexplained_images)\n\n expected = os.path.join(base_dir,\n '17d1b00b81642842e514494a78e804e9a511637c_'\n '10737418240')\n self.assertIn(expected, image_cache_manager.unexplained_images)\n\n unexpected = os.path.join(base_dir, '00000004')\n self.assertNotIn(unexpected, image_cache_manager.unexplained_images)\n\n for ent in image_cache_manager.unexplained_images:\n self.assertTrue(ent.startswith(base_dir))\n\n self.assertEqual(len(image_cache_manager.originals), 2)\n\n expected = os.path.join(base_dir,\n '17d1b00b81642842e514494a78e804e9a511637c')\n self.assertIn(expected, image_cache_manager.originals)\n\n unexpected = os.path.join(base_dir,\n '17d1b00b81642842e514494a78e804e9a511637c_'\n '10737418240')\n self.assertNotIn(unexpected, image_cache_manager.originals)\n\n self.assertEqual(1, len(image_cache_manager.back_swap_images))\n self.assertIn('swap_1000', image_cache_manager.back_swap_images)\n\n def test_list_backing_images_small(self):\n self.stub_out('os.listdir',\n lambda x: ['_base', 'instance-00000001',\n 'instance-00000002', 'instance-00000003'])\n self.stub_out('os.path.exists',\n lambda x: x.find('instance-') != -1)\n self.stubs.Set(libvirt_utils, 'get_disk_backing_file',\n lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm')\n\n found = os.path.join(CONF.instances_path,\n CONF.image_cache_subdirectory_name,\n 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm')\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [found]\n image_cache_manager.instance_names = self.stock_instance_names\n\n inuse_images = image_cache_manager._list_backing_images()\n\n self.assertEqual(inuse_images, [found])\n self.assertEqual(len(image_cache_manager.unexplained_images), 0)\n\n def test_list_backing_images_resized(self):\n self.stub_out('os.listdir',\n lambda x: ['_base', 'instance-00000001',\n 'instance-00000002', 'instance-00000003'])\n self.stub_out('os.path.exists',\n lambda x: x.find('instance-') != -1)\n self.stubs.Set(libvirt_utils, 'get_disk_backing_file',\n lambda x: ('e97222e91fc4241f49a7f520d1dcf446751129b3_'\n '10737418240'))\n\n found = os.path.join(CONF.instances_path,\n CONF.image_cache_subdirectory_name,\n 'e97222e91fc4241f49a7f520d1dcf446751129b3_'\n '10737418240')\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [found]\n image_cache_manager.instance_names = self.stock_instance_names\n\n inuse_images = image_cache_manager._list_backing_images()\n\n self.assertEqual(inuse_images, [found])\n self.assertEqual(len(image_cache_manager.unexplained_images), 0)\n\n def test_list_backing_images_instancename(self):\n self.stub_out('os.listdir',\n lambda x: ['_base', 'banana-42-hamster'])\n self.stub_out('os.path.exists',\n lambda x: x.find('banana-42-hamster') != -1)\n self.stubs.Set(libvirt_utils, 'get_disk_backing_file',\n lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm')\n\n found = os.path.join(CONF.instances_path,\n CONF.image_cache_subdirectory_name,\n 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm')\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [found]\n image_cache_manager.instance_names = self.stock_instance_names\n\n inuse_images = image_cache_manager._list_backing_images()\n\n self.assertEqual(inuse_images, [found])\n self.assertEqual(len(image_cache_manager.unexplained_images), 0)\n\n def test_list_backing_images_disk_notexist(self):\n self.stub_out('os.listdir',\n lambda x: ['_base', 'banana-42-hamster'])\n self.stub_out('os.path.exists',\n lambda x: x.find('banana-42-hamster') != -1)\n\n def fake_get_disk(disk_path):\n raise processutils.ProcessExecutionError()\n\n self.stubs.Set(libvirt_utils, 'get_disk_backing_file', fake_get_disk)\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = []\n image_cache_manager.instance_names = self.stock_instance_names\n\n self.assertRaises(processutils.ProcessExecutionError,\n image_cache_manager._list_backing_images)\n\n def test_find_base_file_nothing(self):\n self.stub_out('os.path.exists', lambda x: False)\n\n base_dir = '/var/lib/nova/instances/_base'\n fingerprint = '549867354867'\n image_cache_manager = imagecache.ImageCacheManager()\n res = list(image_cache_manager._find_base_file(base_dir, fingerprint))\n\n self.assertEqual(0, len(res))\n\n def test_find_base_file_small(self):\n fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a'\n self.stub_out('os.path.exists',\n lambda x: x.endswith('%s_sm' % fingerprint))\n\n base_dir = '/var/lib/nova/instances/_base'\n image_cache_manager = imagecache.ImageCacheManager()\n res = list(image_cache_manager._find_base_file(base_dir, fingerprint))\n\n base_file = os.path.join(base_dir, fingerprint + '_sm')\n self.assertEqual(res, [(base_file, True, False)])\n\n def test_find_base_file_resized(self):\n fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a'\n listing = ['00000001',\n 'ephemeral_0_20_None',\n '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240',\n '00000004']\n\n self.stub_out('os.listdir', lambda x: listing)\n self.stub_out('os.path.exists',\n lambda x: x.endswith('%s_10737418240' % fingerprint))\n self.stub_out('os.path.isfile', lambda x: True)\n\n base_dir = '/var/lib/nova/instances/_base'\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._list_base_images(base_dir)\n res = list(image_cache_manager._find_base_file(base_dir, fingerprint))\n\n base_file = os.path.join(base_dir, fingerprint + '_10737418240')\n self.assertEqual(res, [(base_file, False, True)])\n\n def test_find_base_file_all(self):\n fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a'\n listing = ['00000001',\n 'ephemeral_0_20_None',\n '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_sm',\n '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240',\n '00000004']\n\n self.stub_out('os.listdir', lambda x: listing)\n self.stub_out('os.path.exists', lambda x: True)\n self.stub_out('os.path.isfile', lambda x: True)\n\n base_dir = '/var/lib/nova/instances/_base'\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._list_base_images(base_dir)\n res = list(image_cache_manager._find_base_file(base_dir, fingerprint))\n\n base_file1 = os.path.join(base_dir, fingerprint)\n base_file2 = os.path.join(base_dir, fingerprint + '_sm')\n base_file3 = os.path.join(base_dir, fingerprint + '_10737418240')\n self.assertEqual(res, [(base_file1, False, False),\n (base_file2, True, False),\n (base_file3, False, True)])\n\n @contextlib.contextmanager\n def _make_base_file(self, checksum=True, lock=True):\n \"\"\"Make a base file for testing.\"\"\"\n\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n fname = os.path.join(tmpdir, 'aaa')\n\n base_file = open(fname, 'w')\n base_file.write('data')\n base_file.close()\n\n if lock:\n lockdir = os.path.join(tmpdir, 'locks')\n lockname = os.path.join(lockdir, 'nova-aaa')\n os.mkdir(lockdir)\n lock_file = open(lockname, 'w')\n lock_file.write('data')\n lock_file.close()\n\n base_file = open(fname, 'r')\n\n if checksum:\n imagecache.write_stored_checksum(fname)\n\n base_file.close()\n yield fname\n\n def test_remove_base_file(self):\n with self._make_base_file() as fname:\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._remove_base_file(fname)\n info_fname = imagecache.get_info_filename(fname)\n\n lock_name = 'nova-' + os.path.split(fname)[-1]\n lock_dir = os.path.join(CONF.instances_path, 'locks')\n lock_file = os.path.join(lock_dir, lock_name)\n\n # Files are initially too new to delete\n self.assertTrue(os.path.exists(fname))\n self.assertTrue(os.path.exists(info_fname))\n self.assertTrue(os.path.exists(lock_file))\n\n # Old files get cleaned up though\n os.utime(fname, (-1, time.time() - 3601))\n image_cache_manager._remove_base_file(fname)\n\n self.assertFalse(os.path.exists(fname))\n self.assertFalse(os.path.exists(info_fname))\n self.assertFalse(os.path.exists(lock_file))\n\n def test_remove_base_file_original(self):\n with self._make_base_file() as fname:\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.originals = [fname]\n image_cache_manager._remove_base_file(fname)\n info_fname = imagecache.get_info_filename(fname)\n\n # Files are initially too new to delete\n self.assertTrue(os.path.exists(fname))\n self.assertTrue(os.path.exists(info_fname))\n\n # This file should stay longer than a resized image\n os.utime(fname, (-1, time.time() - 3601))\n image_cache_manager._remove_base_file(fname)\n\n self.assertTrue(os.path.exists(fname))\n self.assertTrue(os.path.exists(info_fname))\n\n # Originals don't stay forever though\n os.utime(fname, (-1, time.time() - 3600 * 25))\n image_cache_manager._remove_base_file(fname)\n\n self.assertFalse(os.path.exists(fname))\n self.assertFalse(os.path.exists(info_fname))\n\n def test_remove_base_file_dne(self):\n # This test is solely to execute the \"does not exist\" code path. We\n # don't expect the method being tested to do anything in this case.\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n\n fname = os.path.join(tmpdir, 'aaa')\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._remove_base_file(fname)\n\n def test_remove_base_file_oserror(self):\n with intercept_log_messages() as stream:\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n\n fname = os.path.join(tmpdir, 'aaa')\n\n os.mkdir(fname)\n os.utime(fname, (-1, time.time() - 3601))\n\n # This will raise an OSError because of file permissions\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._remove_base_file(fname)\n\n self.assertTrue(os.path.exists(fname))\n self.assertNotEqual(stream.getvalue().find('Failed to remove'),\n -1)\n\n def test_handle_base_image_unused(self):\n img = '123'\n\n with self._make_base_file() as fname:\n os.utime(fname, (-1, time.time() - 3601))\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [fname]\n image_cache_manager._handle_base_image(img, fname)\n\n self.assertEqual(image_cache_manager.unexplained_images, [])\n self.assertEqual(image_cache_manager.removable_base_files,\n [fname])\n self.assertEqual(image_cache_manager.corrupt_base_files, [])\n\n @mock.patch.object(libvirt_utils, 'update_mtime')\n def test_handle_base_image_used(self, mock_mtime):\n img = '123'\n\n with self._make_base_file() as fname:\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [fname]\n image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])}\n image_cache_manager._handle_base_image(img, fname)\n\n mock_mtime.assert_called_once_with(fname)\n self.assertEqual(image_cache_manager.unexplained_images, [])\n self.assertEqual(image_cache_manager.removable_base_files, [])\n self.assertEqual(image_cache_manager.corrupt_base_files, [])\n\n @mock.patch.object(libvirt_utils, 'update_mtime')\n def test_handle_base_image_used_remotely(self, mock_mtime):\n img = '123'\n\n with self._make_base_file() as fname:\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [fname]\n image_cache_manager.used_images = {'123': (0, 1, ['banana-42'])}\n image_cache_manager._handle_base_image(img, fname)\n\n mock_mtime.assert_called_once_with(fname)\n self.assertEqual(image_cache_manager.unexplained_images, [])\n self.assertEqual(image_cache_manager.removable_base_files, [])\n self.assertEqual(image_cache_manager.corrupt_base_files, [])\n\n def test_handle_base_image_absent(self):\n img = '123'\n\n with intercept_log_messages() as stream:\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])}\n image_cache_manager._handle_base_image(img, None)\n\n self.assertEqual(image_cache_manager.unexplained_images, [])\n self.assertEqual(image_cache_manager.removable_base_files, [])\n self.assertEqual(image_cache_manager.corrupt_base_files, [])\n self.assertNotEqual(stream.getvalue().find('an absent base file'),\n -1)\n\n def test_handle_base_image_used_missing(self):\n img = '123'\n\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n\n fname = os.path.join(tmpdir, 'aaa')\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [fname]\n image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])}\n image_cache_manager._handle_base_image(img, fname)\n\n self.assertEqual(image_cache_manager.unexplained_images, [])\n self.assertEqual(image_cache_manager.removable_base_files, [])\n self.assertEqual(image_cache_manager.corrupt_base_files, [])\n\n @mock.patch.object(libvirt_utils, 'update_mtime')\n def test_handle_base_image_checksum_fails(self, mock_mtime):\n self.flags(checksum_base_images=True, group='libvirt')\n\n img = '123'\n\n with self._make_base_file() as fname:\n with open(fname, 'w') as f:\n f.write('banana')\n\n d = {'sha1': '21323454'}\n with open('%s.info' % fname, 'w') as f:\n f.write(jsonutils.dumps(d))\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.unexplained_images = [fname]\n image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])}\n image_cache_manager._handle_base_image(img, fname)\n\n mock_mtime.assert_called_once_with(fname)\n self.assertEqual(image_cache_manager.unexplained_images, [])\n self.assertEqual(image_cache_manager.removable_base_files, [])\n self.assertEqual(image_cache_manager.corrupt_base_files,\n [fname])\n\n @mock.patch.object(libvirt_utils, 'update_mtime')\n @mock.patch.object(lockutils, 'external_lock')\n def test_verify_base_images(self, mock_lock, mock_mtime):\n hashed_1 = '356a192b7913b04c54574d18c28d46e6395428ab'\n hashed_21 = '472b07b9fcf2c2451e8781e944bf5f77cd8457c8'\n hashed_22 = '12c6fc06c99a462375eeb3f43dfd832b08ca9e17'\n hashed_42 = '92cfceb39d57d914ed8b14d0e37643de0797ae56'\n\n self.flags(instances_path='/instance_path',\n image_cache_subdirectory_name='_base')\n\n base_file_list = ['00000001',\n 'ephemeral_0_20_None',\n 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm',\n 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm',\n hashed_42,\n hashed_1,\n hashed_21,\n hashed_22,\n '%s_5368709120' % hashed_1,\n '%s_10737418240' % hashed_1,\n '00000004']\n\n def fq_path(path):\n return os.path.join('/instance_path/_base/', path)\n\n # Fake base directory existence\n orig_exists = os.path.exists\n\n def exists(path):\n # The python coverage tool got angry with my overly broad mocks\n if not path.startswith('/instance_path'):\n return orig_exists(path)\n\n if path in ['/instance_path',\n '/instance_path/_base',\n '/instance_path/instance-1/disk',\n '/instance_path/instance-2/disk',\n '/instance_path/instance-3/disk',\n '/instance_path/_base/%s.info' % hashed_42]:\n return True\n\n for p in base_file_list:\n if path == fq_path(p):\n return True\n if path == fq_path(p) + '.info':\n return False\n\n if path in ['/instance_path/_base/%s_sm' % i for i in [hashed_1,\n hashed_21,\n hashed_22,\n hashed_42]]:\n return False\n\n self.fail('Unexpected path existence check: %s' % path)\n\n self.stub_out('os.path.exists', lambda x: exists(x))\n\n # Fake up some instances in the instances directory\n orig_listdir = os.listdir\n\n def listdir(path):\n # The python coverage tool got angry with my overly broad mocks\n if not path.startswith('/instance_path'):\n return orig_listdir(path)\n\n if path == '/instance_path':\n return ['instance-1', 'instance-2', 'instance-3', '_base']\n\n if path == '/instance_path/_base':\n return base_file_list\n\n self.fail('Unexpected directory listed: %s' % path)\n\n self.stub_out('os.listdir', lambda x: listdir(x))\n\n # Fake isfile for these faked images in _base\n orig_isfile = os.path.isfile\n\n def isfile(path):\n # The python coverage tool got angry with my overly broad mocks\n if not path.startswith('/instance_path'):\n return orig_isfile(path)\n\n for p in base_file_list:\n if path == fq_path(p):\n return True\n\n self.fail('Unexpected isfile call: %s' % path)\n\n self.stub_out('os.path.isfile', lambda x: isfile(x))\n\n # Fake the database call which lists running instances\n instances = [{'image_ref': '1',\n 'host': CONF.host,\n 'name': 'instance-1',\n 'uuid': '123',\n 'vm_state': '',\n 'task_state': ''},\n {'image_ref': '1',\n 'kernel_id': '21',\n 'ramdisk_id': '22',\n 'host': CONF.host,\n 'name': 'instance-2',\n 'uuid': '456',\n 'vm_state': '',\n 'task_state': ''}]\n all_instances = [fake_instance.fake_instance_obj(None, **instance)\n for instance in instances]\n image_cache_manager = imagecache.ImageCacheManager()\n\n # Fake the utils call which finds the backing image\n def get_disk_backing_file(path):\n if path in ['/instance_path/instance-1/disk',\n '/instance_path/instance-2/disk']:\n return fq_path('%s_5368709120' % hashed_1)\n self.fail('Unexpected backing file lookup: %s' % path)\n\n self.stubs.Set(libvirt_utils, 'get_disk_backing_file',\n lambda x: get_disk_backing_file(x))\n\n # Fake out verifying checksums, as that is tested elsewhere\n self.stubs.Set(image_cache_manager, '_verify_checksum',\n lambda x, y: True)\n\n # Fake getmtime as well\n orig_getmtime = os.path.getmtime\n\n def getmtime(path):\n if not path.startswith('/instance_path'):\n return orig_getmtime(path)\n\n return 1000000\n\n self.stub_out('os.path.getmtime', lambda x: getmtime(x))\n\n # Make sure we don't accidentally remove a real file\n orig_remove = os.remove\n\n def remove(path):\n if not path.startswith('/instance_path'):\n return orig_remove(path)\n\n # Don't try to remove fake files\n return\n\n self.stub_out('os.remove', lambda x: remove(x))\n\n self.mox.StubOutWithMock(objects.block_device.BlockDeviceMappingList,\n 'get_by_instance_uuid')\n\n ctxt = context.get_admin_context()\n objects.block_device.BlockDeviceMappingList.get_by_instance_uuid(\n ctxt, '123').AndReturn(None)\n objects.block_device.BlockDeviceMappingList.get_by_instance_uuid(\n ctxt, '456').AndReturn(None)\n\n self.mox.ReplayAll()\n # And finally we can make the call we're actually testing...\n # The argument here should be a context, but it is mocked out\n image_cache_manager.update(ctxt, all_instances)\n\n # Verify\n active = [fq_path(hashed_1), fq_path('%s_5368709120' % hashed_1),\n fq_path(hashed_21), fq_path(hashed_22)]\n for act in active:\n self.assertIn(act, image_cache_manager.active_base_files)\n self.assertEqual(len(image_cache_manager.active_base_files),\n len(active))\n\n for rem in [fq_path('e97222e91fc4241f49a7f520d1dcf446751129b3_sm'),\n fq_path('e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm'),\n fq_path(hashed_42),\n fq_path('%s_10737418240' % hashed_1)]:\n self.assertIn(rem, image_cache_manager.removable_base_files)\n\n # Ensure there are no \"corrupt\" images as well\n self.assertEqual(len(image_cache_manager.corrupt_base_files), 0)\n\n def test_verify_base_images_no_base(self):\n self.flags(instances_path='/tmp/no/such/dir/name/please')\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.update(None, [])\n\n def test_is_valid_info_file(self):\n hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3'\n\n self.flags(instances_path='/tmp/no/such/dir/name/please')\n self.flags(image_info_filename_pattern=('$instances_path/_base/'\n '%(image)s.info'),\n group='libvirt')\n base_filename = os.path.join(CONF.instances_path, '_base', hashed)\n\n is_valid_info_file = imagecache.is_valid_info_file\n self.assertFalse(is_valid_info_file('banana'))\n self.assertFalse(is_valid_info_file(\n os.path.join(CONF.instances_path, '_base', '00000001')))\n self.assertFalse(is_valid_info_file(base_filename))\n self.assertFalse(is_valid_info_file(base_filename + '.sha1'))\n self.assertTrue(is_valid_info_file(base_filename + '.info'))\n\n def test_configured_checksum_path(self):\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n\n # Ensure there is a base directory\n os.mkdir(os.path.join(tmpdir, '_base'))\n\n # Fake the database call which lists running instances\n instances = [{'image_ref': '1',\n 'host': CONF.host,\n 'name': 'instance-1',\n 'uuid': '123',\n 'vm_state': '',\n 'task_state': ''},\n {'image_ref': '1',\n 'host': CONF.host,\n 'name': 'instance-2',\n 'uuid': '456',\n 'vm_state': '',\n 'task_state': ''}]\n\n all_instances = []\n for instance in instances:\n all_instances.append(fake_instance.fake_instance_obj(\n None, **instance))\n\n def touch(filename):\n f = open(filename, 'w')\n f.write('Touched')\n f.close()\n\n old = time.time() - (25 * 3600)\n hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3'\n base_filename = os.path.join(tmpdir, hashed)\n touch(base_filename)\n touch(base_filename + '.info')\n os.utime(base_filename + '.info', (old, old))\n touch(base_filename + '.info')\n os.utime(base_filename + '.info', (old, old))\n\n self.mox.StubOutWithMock(\n objects.block_device.BlockDeviceMappingList,\n 'get_by_instance_uuid')\n\n ctxt = context.get_admin_context()\n objects.block_device.BlockDeviceMappingList.get_by_instance_uuid(\n ctxt, '123').AndReturn(None)\n objects.block_device.BlockDeviceMappingList.get_by_instance_uuid(\n ctxt, '456').AndReturn(None)\n\n self.mox.ReplayAll()\n\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager.update(ctxt,\n all_instances)\n\n self.assertTrue(os.path.exists(base_filename))\n self.assertTrue(os.path.exists(base_filename + '.info'))\n\n def test_run_image_cache_manager_pass(self):\n was = {'called': False}\n\n def fake_get_all_by_filters(context, *args, **kwargs):\n was['called'] = True\n instances = []\n for x in range(2):\n instances.append(fake_instance.fake_db_instance(\n image_ref='1',\n uuid=x,\n name=x,\n vm_state='',\n task_state=''))\n return instances\n\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n\n self.stub_out('nova.db.instance_get_all_by_filters',\n fake_get_all_by_filters)\n compute = importutils.import_object(CONF.compute_manager)\n self.flags(use_local=True, group='conductor')\n compute.conductor_api = conductor.API()\n ctxt = context.get_admin_context()\n compute._run_image_cache_manager_pass(ctxt)\n self.assertTrue(was['called'])\n\n def test_store_swap_image(self):\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._store_swap_image('swap_')\n image_cache_manager._store_swap_image('swap_123')\n image_cache_manager._store_swap_image('swap_456')\n image_cache_manager._store_swap_image('swap_abc')\n image_cache_manager._store_swap_image('123_swap')\n image_cache_manager._store_swap_image('swap_129_')\n\n self.assertEqual(len(image_cache_manager.back_swap_images), 2)\n expect_set = set(['swap_123', 'swap_456'])\n self.assertEqual(image_cache_manager.back_swap_images, expect_set)\n\n @mock.patch.object(lockutils, 'external_lock')\n @mock.patch.object(libvirt_utils, 'update_mtime')\n @mock.patch('os.path.exists', return_value=True)\n @mock.patch('os.path.getmtime')\n @mock.patch('os.remove')\n def test_age_and_verify_swap_images(self, mock_remove, mock_getmtime,\n mock_exist, mock_mtime, mock_lock):\n image_cache_manager = imagecache.ImageCacheManager()\n expected_remove = set()\n expected_exist = set(['swap_128', 'swap_256'])\n\n image_cache_manager.back_swap_images.add('swap_128')\n image_cache_manager.back_swap_images.add('swap_256')\n\n image_cache_manager.used_swap_images.add('swap_128')\n\n def getmtime(path):\n return time.time() - 1000000\n\n mock_getmtime.side_effect = getmtime\n\n def removefile(path):\n if not path.startswith('/tmp_age_test'):\n return os.remove(path)\n\n fn = os.path.split(path)[-1]\n expected_remove.add(fn)\n expected_exist.remove(fn)\n\n mock_remove.side_effect = removefile\n\n image_cache_manager._age_and_verify_swap_images(None, '/tmp_age_test')\n self.assertEqual(1, len(expected_exist))\n self.assertEqual(1, len(expected_remove))\n self.assertIn('swap_128', expected_exist)\n self.assertIn('swap_256', expected_remove)\n\n @mock.patch.object(utils, 'synchronized')\n @mock.patch.object(imagecache.ImageCacheManager, '_get_age_of_file',\n return_value=(True, 100))\n def test_lock_acquired_on_removing_old_enough_files(self, mock_get_age,\n mock_synchronized):\n base_file = '/tmp_age_test'\n lock_path = os.path.join(CONF.instances_path, 'locks')\n lock_file = os.path.split(base_file)[-1]\n image_cache_manager = imagecache.ImageCacheManager()\n image_cache_manager._remove_old_enough_file(\n base_file, 60, remove_sig=False, remove_lock=False)\n mock_synchronized.assert_called_once_with(lock_file, external=True,\n lock_path=lock_path)\n\n\nclass VerifyChecksumTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super(VerifyChecksumTestCase, self).setUp()\n self.img = {'container_format': 'ami', 'id': '42'}\n self.flags(checksum_base_images=True, group='libvirt')\n\n def _make_checksum(self, tmpdir):\n testdata = ('OpenStack Software delivers a massively scalable cloud '\n 'operating system.')\n\n fname = os.path.join(tmpdir, 'aaa')\n info_fname = imagecache.get_info_filename(fname)\n\n with open(fname, 'w') as f:\n f.write(testdata)\n\n return fname, info_fname, testdata\n\n def _write_file(self, info_fname, info_attr, testdata):\n f = open(info_fname, 'w')\n if info_attr == \"csum valid\":\n csum = hashlib.sha1()\n csum.update(testdata)\n f.write('{\"sha1\": \"%s\"}\\n' % csum.hexdigest())\n elif info_attr == \"csum invalid, not json\":\n f.write('banana')\n else:\n f.write('{\"sha1\": \"banana\"}')\n f.close()\n\n def _check_body(self, tmpdir, info_attr):\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n fname, info_fname, testdata = self._make_checksum(tmpdir)\n self._write_file(info_fname, info_attr, testdata)\n image_cache_manager = imagecache.ImageCacheManager()\n return image_cache_manager, fname\n\n def test_verify_checksum(self):\n with utils.tempdir() as tmpdir:\n image_cache_manager, fname = self._check_body(tmpdir, \"csum valid\")\n res = image_cache_manager._verify_checksum(self.img, fname)\n self.assertTrue(res)\n\n def test_verify_checksum_disabled(self):\n self.flags(checksum_base_images=False, group='libvirt')\n with utils.tempdir() as tmpdir:\n image_cache_manager, fname = self._check_body(tmpdir, \"csum valid\")\n res = image_cache_manager._verify_checksum(self.img, fname)\n self.assertIsNone(res)\n\n def test_verify_checksum_invalid_json(self):\n with intercept_log_messages() as stream:\n with utils.tempdir() as tmpdir:\n image_cache_manager, fname = (\n self._check_body(tmpdir, \"csum invalid, not json\"))\n res = image_cache_manager._verify_checksum(\n self.img, fname, create_if_missing=False)\n self.assertFalse(res)\n log = stream.getvalue()\n\n # NOTE(mikal): this is a skip not a fail because the file is\n # present, but is not in valid JSON format and therefore is\n # skipped.\n self.assertNotEqual(log.find('image verification skipped'), -1)\n\n def test_verify_checksum_invalid_repaired(self):\n with utils.tempdir() as tmpdir:\n image_cache_manager, fname = (\n self._check_body(tmpdir, \"csum invalid, not json\"))\n res = image_cache_manager._verify_checksum(\n self.img, fname, create_if_missing=True)\n self.assertIsNone(res)\n\n def test_verify_checksum_invalid(self):\n with intercept_log_messages() as stream:\n with utils.tempdir() as tmpdir:\n image_cache_manager, fname = (\n self._check_body(tmpdir, \"csum invalid, valid json\"))\n res = image_cache_manager._verify_checksum(self.img, fname)\n self.assertFalse(res)\n log = stream.getvalue()\n self.assertNotEqual(log.find('image verification failed'), -1)\n\n def test_verify_checksum_file_missing(self):\n with utils.tempdir() as tmpdir:\n self.flags(instances_path=tmpdir)\n self.flags(image_info_filename_pattern=('$instances_path/'\n '%(image)s.info'),\n group='libvirt')\n fname, info_fname, testdata = self._make_checksum(tmpdir)\n\n image_cache_manager = imagecache.ImageCacheManager()\n res = image_cache_manager._verify_checksum('aaa', fname)\n self.assertIsNone(res)\n\n # Checksum requests for a file with no checksum now have the\n # side effect of creating the checksum\n self.assertTrue(os.path.exists(info_fname))\n"},"license":{"kind":"string","value":"apache-2.0"}}},{"rowIdx":476122,"cells":{"repo_name":{"kind":"string","value":"2014c2g23/2015cda"},"path":{"kind":"string","value":"static/Brython3.1.1-20150328-091302/Lib/unittest/test/test_assertions.py"},"copies":{"kind":"string","value":"738"},"size":{"kind":"string","value":"15398"},"content":{"kind":"string","value":"import datetime\nimport warnings\nimport unittest\nfrom itertools import product\n\n\nclass Test_Assertions(unittest.TestCase):\n def test_AlmostEqual(self):\n self.assertAlmostEqual(1.00000001, 1.0)\n self.assertNotAlmostEqual(1.0000001, 1.0)\n self.assertRaises(self.failureException,\n self.assertAlmostEqual, 1.0000001, 1.0)\n self.assertRaises(self.failureException,\n self.assertNotAlmostEqual, 1.00000001, 1.0)\n\n self.assertAlmostEqual(1.1, 1.0, places=0)\n self.assertRaises(self.failureException,\n self.assertAlmostEqual, 1.1, 1.0, places=1)\n\n self.assertAlmostEqual(0, .1+.1j, places=0)\n self.assertNotAlmostEqual(0, .1+.1j, places=1)\n self.assertRaises(self.failureException,\n self.assertAlmostEqual, 0, .1+.1j, places=1)\n self.assertRaises(self.failureException,\n self.assertNotAlmostEqual, 0, .1+.1j, places=0)\n\n self.assertAlmostEqual(float('inf'), float('inf'))\n self.assertRaises(self.failureException, self.assertNotAlmostEqual,\n float('inf'), float('inf'))\n\n def test_AmostEqualWithDelta(self):\n self.assertAlmostEqual(1.1, 1.0, delta=0.5)\n self.assertAlmostEqual(1.0, 1.1, delta=0.5)\n self.assertNotAlmostEqual(1.1, 1.0, delta=0.05)\n self.assertNotAlmostEqual(1.0, 1.1, delta=0.05)\n\n self.assertRaises(self.failureException, self.assertAlmostEqual,\n 1.1, 1.0, delta=0.05)\n self.assertRaises(self.failureException, self.assertNotAlmostEqual,\n 1.1, 1.0, delta=0.5)\n\n self.assertRaises(TypeError, self.assertAlmostEqual,\n 1.1, 1.0, places=2, delta=2)\n self.assertRaises(TypeError, self.assertNotAlmostEqual,\n 1.1, 1.0, places=2, delta=2)\n\n first = datetime.datetime.now()\n second = first + datetime.timedelta(seconds=10)\n self.assertAlmostEqual(first, second,\n delta=datetime.timedelta(seconds=20))\n self.assertNotAlmostEqual(first, second,\n delta=datetime.timedelta(seconds=5))\n\n def test_assertRaises(self):\n def _raise(e):\n raise e\n self.assertRaises(KeyError, _raise, KeyError)\n self.assertRaises(KeyError, _raise, KeyError(\"key\"))\n try:\n self.assertRaises(KeyError, lambda: None)\n except self.failureException as e:\n self.assertIn(\"KeyError not raised\", str(e))\n else:\n self.fail(\"assertRaises() didn't fail\")\n try:\n self.assertRaises(KeyError, _raise, ValueError)\n except ValueError:\n pass\n else:\n self.fail(\"assertRaises() didn't let exception pass through\")\n with self.assertRaises(KeyError) as cm:\n try:\n raise KeyError\n except Exception as e:\n exc = e\n raise\n self.assertIs(cm.exception, exc)\n\n with self.assertRaises(KeyError):\n raise KeyError(\"key\")\n try:\n with self.assertRaises(KeyError):\n pass\n except self.failureException as e:\n self.assertIn(\"KeyError not raised\", str(e))\n else:\n self.fail(\"assertRaises() didn't fail\")\n try:\n with self.assertRaises(KeyError):\n raise ValueError\n except ValueError:\n pass\n else:\n self.fail(\"assertRaises() didn't let exception pass through\")\n\n def testAssertNotRegex(self):\n self.assertNotRegex('Ala ma kota', r'r+')\n try:\n self.assertNotRegex('Ala ma kota', r'k.t', 'Message')\n except self.failureException as e:\n self.assertIn(\"'kot'\", e.args[0])\n self.assertIn('Message', e.args[0])\n else:\n self.fail('assertNotRegex should have failed.')\n\n\nclass TestLongMessage(unittest.TestCase):\n \"\"\"Test that the individual asserts honour longMessage.\n This actually tests all the message behaviour for\n asserts that use longMessage.\"\"\"\n\n def setUp(self):\n class TestableTestFalse(unittest.TestCase):\n longMessage = False\n failureException = self.failureException\n\n def testTest(self):\n pass\n\n class TestableTestTrue(unittest.TestCase):\n longMessage = True\n failureException = self.failureException\n\n def testTest(self):\n pass\n\n self.testableTrue = TestableTestTrue('testTest')\n self.testableFalse = TestableTestFalse('testTest')\n\n def testDefault(self):\n self.assertTrue(unittest.TestCase.longMessage)\n\n def test_formatMsg(self):\n self.assertEqual(self.testableFalse._formatMessage(None, \"foo\"), \"foo\")\n self.assertEqual(self.testableFalse._formatMessage(\"foo\", \"bar\"), \"foo\")\n\n self.assertEqual(self.testableTrue._formatMessage(None, \"foo\"), \"foo\")\n self.assertEqual(self.testableTrue._formatMessage(\"foo\", \"bar\"), \"bar : foo\")\n\n # This blows up if _formatMessage uses string concatenation\n self.testableTrue._formatMessage(object(), 'foo')\n\n def test_formatMessage_unicode_error(self):\n one = ''.join(chr(i) for i in range(255))\n # this used to cause a UnicodeDecodeError constructing msg\n self.testableTrue._formatMessage(one, '\\uFFFD')\n\n def assertMessages(self, methodName, args, errors):\n \"\"\"\n Check that methodName(*args) raises the correct error messages.\n errors should be a list of 4 regex that match the error when:\n 1) longMessage = False and no msg passed;\n 2) longMessage = False and msg passed;\n 3) longMessage = True and no msg passed;\n 4) longMessage = True and msg passed;\n \"\"\"\n def getMethod(i):\n useTestableFalse = i < 2\n if useTestableFalse:\n test = self.testableFalse\n else:\n test = self.testableTrue\n return getattr(test, methodName)\n\n for i, expected_regex in enumerate(errors):\n testMethod = getMethod(i)\n kwargs = {}\n withMsg = i % 2\n if withMsg:\n kwargs = {\"msg\": \"oops\"}\n\n with self.assertRaisesRegex(self.failureException,\n expected_regex=expected_regex):\n testMethod(*args, **kwargs)\n\n def testAssertTrue(self):\n self.assertMessages('assertTrue', (False,),\n [\"^False is not true$\", \"^oops$\", \"^False is not true$\",\n \"^False is not true : oops$\"])\n\n def testAssertFalse(self):\n self.assertMessages('assertFalse', (True,),\n [\"^True is not false$\", \"^oops$\", \"^True is not false$\",\n \"^True is not false : oops$\"])\n\n def testNotEqual(self):\n self.assertMessages('assertNotEqual', (1, 1),\n [\"^1 == 1$\", \"^oops$\", \"^1 == 1$\",\n \"^1 == 1 : oops$\"])\n\n def testAlmostEqual(self):\n self.assertMessages('assertAlmostEqual', (1, 2),\n [\"^1 != 2 within 7 places$\", \"^oops$\",\n \"^1 != 2 within 7 places$\", \"^1 != 2 within 7 places : oops$\"])\n\n def testNotAlmostEqual(self):\n self.assertMessages('assertNotAlmostEqual', (1, 1),\n [\"^1 == 1 within 7 places$\", \"^oops$\",\n \"^1 == 1 within 7 places$\", \"^1 == 1 within 7 places : oops$\"])\n\n def test_baseAssertEqual(self):\n self.assertMessages('_baseAssertEqual', (1, 2),\n [\"^1 != 2$\", \"^oops$\", \"^1 != 2$\", \"^1 != 2 : oops$\"])\n\n def testAssertSequenceEqual(self):\n # Error messages are multiline so not testing on full message\n # assertTupleEqual and assertListEqual delegate to this method\n self.assertMessages('assertSequenceEqual', ([], [None]),\n [\"\\+ \\[None\\]$\", \"^oops$\", r\"\\+ \\[None\\]$\",\n r\"\\+ \\[None\\] : oops$\"])\n\n def testAssertSetEqual(self):\n self.assertMessages('assertSetEqual', (set(), set([None])),\n [\"None$\", \"^oops$\", \"None$\",\n \"None : oops$\"])\n\n def testAssertIn(self):\n self.assertMessages('assertIn', (None, []),\n ['^None not found in \\[\\]$', \"^oops$\",\n '^None not found in \\[\\]$',\n '^None not found in \\[\\] : oops$'])\n\n def testAssertNotIn(self):\n self.assertMessages('assertNotIn', (None, [None]),\n ['^None unexpectedly found in \\[None\\]$', \"^oops$\",\n '^None unexpectedly found in \\[None\\]$',\n '^None unexpectedly found in \\[None\\] : oops$'])\n\n def testAssertDictEqual(self):\n self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),\n [r\"\\+ \\{'key': 'value'\\}$\", \"^oops$\",\n \"\\+ \\{'key': 'value'\\}$\",\n \"\\+ \\{'key': 'value'\\} : oops$\"])\n\n def testAssertDictContainsSubset(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", DeprecationWarning)\n\n self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),\n [\"^Missing: 'key'$\", \"^oops$\",\n \"^Missing: 'key'$\",\n \"^Missing: 'key' : oops$\"])\n\n def testAssertMultiLineEqual(self):\n self.assertMessages('assertMultiLineEqual', (\"\", \"foo\"),\n [r\"\\+ foo$\", \"^oops$\",\n r\"\\+ foo$\",\n r\"\\+ foo : oops$\"])\n\n def testAssertLess(self):\n self.assertMessages('assertLess', (2, 1),\n [\"^2 not less than 1$\", \"^oops$\",\n \"^2 not less than 1$\", \"^2 not less than 1 : oops$\"])\n\n def testAssertLessEqual(self):\n self.assertMessages('assertLessEqual', (2, 1),\n [\"^2 not less than or equal to 1$\", \"^oops$\",\n \"^2 not less than or equal to 1$\",\n \"^2 not less than or equal to 1 : oops$\"])\n\n def testAssertGreater(self):\n self.assertMessages('assertGreater', (1, 2),\n [\"^1 not greater than 2$\", \"^oops$\",\n \"^1 not greater than 2$\",\n \"^1 not greater than 2 : oops$\"])\n\n def testAssertGreaterEqual(self):\n self.assertMessages('assertGreaterEqual', (1, 2),\n [\"^1 not greater than or equal to 2$\", \"^oops$\",\n \"^1 not greater than or equal to 2$\",\n \"^1 not greater than or equal to 2 : oops$\"])\n\n def testAssertIsNone(self):\n self.assertMessages('assertIsNone', ('not None',),\n [\"^'not None' is not None$\", \"^oops$\",\n \"^'not None' is not None$\",\n \"^'not None' is not None : oops$\"])\n\n def testAssertIsNotNone(self):\n self.assertMessages('assertIsNotNone', (None,),\n [\"^unexpectedly None$\", \"^oops$\",\n \"^unexpectedly None$\",\n \"^unexpectedly None : oops$\"])\n\n def testAssertIs(self):\n self.assertMessages('assertIs', (None, 'foo'),\n [\"^None is not 'foo'$\", \"^oops$\",\n \"^None is not 'foo'$\",\n \"^None is not 'foo' : oops$\"])\n\n def testAssertIsNot(self):\n self.assertMessages('assertIsNot', (None, None),\n [\"^unexpectedly identical: None$\", \"^oops$\",\n \"^unexpectedly identical: None$\",\n \"^unexpectedly identical: None : oops$\"])\n\n\n def assertMessagesCM(self, methodName, args, func, errors):\n \"\"\"\n Check that the correct error messages are raised while executing:\n with method(*args):\n func()\n *errors* should be a list of 4 regex that match the error when:\n 1) longMessage = False and no msg passed;\n 2) longMessage = False and msg passed;\n 3) longMessage = True and no msg passed;\n 4) longMessage = True and msg passed;\n \"\"\"\n p = product((self.testableFalse, self.testableTrue),\n ({}, {\"msg\": \"oops\"}))\n for (cls, kwargs), err in zip(p, errors):\n method = getattr(cls, methodName)\n with self.assertRaisesRegex(cls.failureException, err):\n with method(*args, **kwargs) as cm:\n func()\n\n def testAssertRaises(self):\n self.assertMessagesCM('assertRaises', (TypeError,), lambda: None,\n ['^TypeError not raised$', '^oops$',\n '^TypeError not raised$',\n '^TypeError not raised : oops$'])\n\n def testAssertRaisesRegex(self):\n # test error not raised\n self.assertMessagesCM('assertRaisesRegex', (TypeError, 'unused regex'),\n lambda: None,\n ['^TypeError not raised$', '^oops$',\n '^TypeError not raised$',\n '^TypeError not raised : oops$'])\n # test error raised but with wrong message\n def raise_wrong_message():\n raise TypeError('foo')\n self.assertMessagesCM('assertRaisesRegex', (TypeError, 'regex'),\n raise_wrong_message,\n ['^\"regex\" does not match \"foo\"$', '^oops$',\n '^\"regex\" does not match \"foo\"$',\n '^\"regex\" does not match \"foo\" : oops$'])\n\n def testAssertWarns(self):\n self.assertMessagesCM('assertWarns', (UserWarning,), lambda: None,\n ['^UserWarning not triggered$', '^oops$',\n '^UserWarning not triggered$',\n '^UserWarning not triggered : oops$'])\n\n def testAssertWarnsRegex(self):\n # test error not raised\n self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'unused regex'),\n lambda: None,\n ['^UserWarning not triggered$', '^oops$',\n '^UserWarning not triggered$',\n '^UserWarning not triggered : oops$'])\n # test warning raised but with wrong message\n def raise_wrong_message():\n warnings.warn('foo')\n self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'regex'),\n raise_wrong_message,\n ['^\"regex\" does not match \"foo\"$', '^oops$',\n '^\"regex\" does not match \"foo\"$',\n '^\"regex\" does not match \"foo\" : oops$'])\n"},"license":{"kind":"string","value":"gpl-3.0"}}},{"rowIdx":476123,"cells":{"repo_name":{"kind":"string","value":"jamesblunt/sympy"},"path":{"kind":"string","value":"sympy/printing/tests/test_mathematica.py"},"copies":{"kind":"string","value":"93"},"size":{"kind":"string","value":"2612"},"content":{"kind":"string","value":"from sympy.core import (S, pi, oo, symbols, Function,\n Rational, Integer, Tuple)\nfrom sympy.integrals import Integral\nfrom sympy.concrete import Sum\nfrom sympy.functions import exp, sin, cos\n\nfrom sympy import mathematica_code as mcode\n\nx, y, z = symbols('x,y,z')\nf = Function('f')\n\n\ndef test_Integer():\n assert mcode(Integer(67)) == \"67\"\n assert mcode(Integer(-1)) == \"-1\"\n\n\ndef test_Rational():\n assert mcode(Rational(3, 7)) == \"3/7\"\n assert mcode(Rational(18, 9)) == \"2\"\n assert mcode(Rational(3, -7)) == \"-3/7\"\n assert mcode(Rational(-3, -7)) == \"3/7\"\n assert mcode(x + Rational(3, 7)) == \"x + 3/7\"\n assert mcode(Rational(3, 7)*x) == \"(3/7)*x\"\n\n\ndef test_Function():\n assert mcode(f(x, y, z)) == \"f[x, y, z]\"\n assert mcode(sin(x) ** cos(x)) == \"Sin[x]^Cos[x]\"\n\n\ndef test_Pow():\n assert mcode(x**3) == \"x^3\"\n assert mcode(x**(y**3)) == \"x^(y^3)\"\n assert mcode(1/(f(x)*3.5)**(x - y**x)/(x**2 + y)) == \\\n \"(3.5*f[x])^(-x + y^x)/(x^2 + y)\"\n assert mcode(x**-1.0) == 'x^(-1.0)'\n assert mcode(x**Rational(2, 3)) == 'x^(2/3)'\n\n\ndef test_Mul():\n A, B, C, D = symbols('A B C D', commutative=False)\n assert mcode(x*y*z) == \"x*y*z\"\n assert mcode(x*y*A) == \"x*y*A\"\n assert mcode(x*y*A*B) == \"x*y*A**B\"\n assert mcode(x*y*A*B*C) == \"x*y*A**B**C\"\n assert mcode(x*A*B*(C + D)*A*y) == \"x*y*A**B**(C + D)**A\"\n\n\ndef test_constants():\n assert mcode(pi) == \"Pi\"\n assert mcode(oo) == \"Infinity\"\n assert mcode(S.NegativeInfinity) == \"-Infinity\"\n assert mcode(S.EulerGamma) == \"EulerGamma\"\n assert mcode(S.Catalan) == \"Catalan\"\n assert mcode(S.Exp1) == \"E\"\n\n\ndef test_containers():\n assert mcode([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \\\n \"{1, 2, 3, {4, 5, {6, 7}}, 8, {9, 10}, 11}\"\n assert mcode((1, 2, (3, 4))) == \"{1, 2, {3, 4}}\"\n assert mcode([1]) == \"{1}\"\n assert mcode((1,)) == \"{1}\"\n assert mcode(Tuple(*[1, 2, 3])) == \"{1, 2, 3}\"\n\n\ndef test_Integral():\n assert mcode(Integral(sin(sin(x)), x)) == \"Hold[Integrate[Sin[Sin[x]], x]]\"\n assert mcode(Integral(exp(-x**2 - y**2),\n (x, -oo, oo),\n (y, -oo, oo))) == \\\n \"Hold[Integrate[Exp[-x^2 - y^2], {x, -Infinity, Infinity}, \" \\\n \"{y, -Infinity, Infinity}]]\"\n\n\ndef test_Sum():\n assert mcode(Sum(sin(x), (x, 0, 10))) == \"Hold[Sum[Sin[x], {x, 0, 10}]]\"\n assert mcode(Sum(exp(-x**2 - y**2),\n (x, -oo, oo),\n (y, -oo, oo))) == \\\n \"Hold[Sum[Exp[-x^2 - y^2], {x, -Infinity, Infinity}, \" \\\n \"{y, -Infinity, Infinity}]]\"\n"},"license":{"kind":"string","value":"bsd-3-clause"}}},{"rowIdx":476124,"cells":{"repo_name":{"kind":"string","value":"40223151/2015cd_midterm"},"path":{"kind":"string","value":"static/Brython3.1.1-20150328-091302/Lib/unittest/case.py"},"copies":{"kind":"string","value":"743"},"size":{"kind":"string","value":"48873"},"content":{"kind":"string","value":"\"\"\"Test case implementation\"\"\"\n\nimport sys\nimport functools\nimport difflib\nimport pprint\nimport re\nimport warnings\nimport collections\n\nfrom . import result\nfrom .util import (strclass, safe_repr, _count_diff_all_purpose,\n _count_diff_hashable)\n\n__unittest = True\n\n\nDIFF_OMITTED = ('\\nDiff is %s characters long. '\n 'Set self.maxDiff to None to see it.')\n\nclass SkipTest(Exception):\n \"\"\"\n Raise this exception in a test to skip it.\n\n Usually you can use TestCase.skipTest() or one of the skipping decorators\n instead of raising this directly.\n \"\"\"\n\nclass _ExpectedFailure(Exception):\n \"\"\"\n Raise this when a test is expected to fail.\n\n This is an implementation detail.\n \"\"\"\n\n def __init__(self, exc_info):\n super(_ExpectedFailure, self).__init__()\n self.exc_info = exc_info\n\nclass _UnexpectedSuccess(Exception):\n \"\"\"\n The test was supposed to fail, but it didn't!\n \"\"\"\n\n\nclass _Outcome(object):\n def __init__(self):\n self.success = True\n self.skipped = None\n self.unexpectedSuccess = None\n self.expectedFailure = None\n self.errors = []\n self.failures = []\n\n\ndef _id(obj):\n return obj\n\ndef skip(reason):\n \"\"\"\n Unconditionally skip a test.\n \"\"\"\n def decorator(test_item):\n if not isinstance(test_item, type):\n @functools.wraps(test_item)\n def skip_wrapper(*args, **kwargs):\n raise SkipTest(reason)\n test_item = skip_wrapper\n\n test_item.__unittest_skip__ = True\n test_item.__unittest_skip_why__ = reason\n return test_item\n return decorator\n\ndef skipIf(condition, reason):\n \"\"\"\n Skip a test if the condition is true.\n \"\"\"\n if condition:\n return skip(reason)\n return _id\n\ndef skipUnless(condition, reason):\n \"\"\"\n Skip a test unless the condition is true.\n \"\"\"\n if not condition:\n return skip(reason)\n return _id\n\n\ndef expectedFailure(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception:\n raise _ExpectedFailure(sys.exc_info())\n raise _UnexpectedSuccess\n return wrapper\n\n\nclass _AssertRaisesBaseContext(object):\n\n def __init__(self, expected, test_case, callable_obj=None,\n expected_regex=None):\n self.expected = expected\n self.test_case = test_case\n if callable_obj is not None:\n try:\n self.obj_name = callable_obj.__name__\n except AttributeError:\n self.obj_name = str(callable_obj)\n else:\n self.obj_name = None\n if isinstance(expected_regex, (bytes, str)):\n expected_regex = re.compile(expected_regex)\n self.expected_regex = expected_regex\n self.msg = None\n\n def _raiseFailure(self, standardMsg):\n msg = self.test_case._formatMessage(self.msg, standardMsg)\n raise self.test_case.failureException(msg)\n\n def handle(self, name, callable_obj, args, kwargs):\n \"\"\"\n If callable_obj is None, assertRaises/Warns is being used as a\n context manager, so check for a 'msg' kwarg and return self.\n If callable_obj is not None, call it passing args and kwargs.\n \"\"\"\n if callable_obj is None:\n self.msg = kwargs.pop('msg', None)\n return self\n with self:\n callable_obj(*args, **kwargs)\n\n\n\nclass _AssertRaisesContext(_AssertRaisesBaseContext):\n \"\"\"A context manager used to implement TestCase.assertRaises* methods.\"\"\"\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, tb):\n if exc_type is None:\n try:\n exc_name = self.expected.__name__\n except AttributeError:\n exc_name = str(self.expected)\n if self.obj_name:\n self._raiseFailure(\"{} not raised by {}\".format(exc_name,\n self.obj_name))\n else:\n self._raiseFailure(\"{} not raised\".format(exc_name))\n if not issubclass(exc_type, self.expected):\n # let unexpected exceptions pass through\n return False\n # store exception, without traceback, for later retrieval\n self.exception = exc_value.with_traceback(None)\n if self.expected_regex is None:\n return True\n\n expected_regex = self.expected_regex\n if not expected_regex.search(str(exc_value)):\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n expected_regex.pattern, str(exc_value)))\n return True\n\n\nclass _AssertWarnsContext(_AssertRaisesBaseContext):\n \"\"\"A context manager used to implement TestCase.assertWarns* methods.\"\"\"\n\n def __enter__(self):\n # The __warningregistry__'s need to be in a pristine state for tests\n # to work properly.\n for v in sys.modules.values():\n if getattr(v, '__warningregistry__', None):\n v.__warningregistry__ = {}\n self.warnings_manager = warnings.catch_warnings(record=True)\n self.warnings = self.warnings_manager.__enter__()\n warnings.simplefilter(\"always\", self.expected)\n return self\n\n def __exit__(self, exc_type, exc_value, tb):\n self.warnings_manager.__exit__(exc_type, exc_value, tb)\n if exc_type is not None:\n # let unexpected exceptions pass through\n return\n try:\n exc_name = self.expected.__name__\n except AttributeError:\n exc_name = str(self.expected)\n first_matching = None\n for m in self.warnings:\n w = m.message\n if not isinstance(w, self.expected):\n continue\n if first_matching is None:\n first_matching = w\n if (self.expected_regex is not None and\n not self.expected_regex.search(str(w))):\n continue\n # store warning for later retrieval\n self.warning = w\n self.filename = m.filename\n self.lineno = m.lineno\n return\n # Now we simply try to choose a helpful failure message\n if first_matching is not None:\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n self.expected_regex.pattern, str(first_matching)))\n if self.obj_name:\n self._raiseFailure(\"{} not triggered by {}\".format(exc_name,\n self.obj_name))\n else:\n self._raiseFailure(\"{} not triggered\".format(exc_name))\n\n\nclass TestCase(object):\n \"\"\"A class whose instances are single test cases.\n\n By default, the test code itself should be placed in a method named\n 'runTest'.\n\n If the fixture may be used for many test cases, create as\n many test methods as are needed. When instantiating such a TestCase\n subclass, specify in the constructor arguments the name of the test method\n that the instance is to execute.\n\n Test authors should subclass TestCase for their own tests. Construction\n and deconstruction of the test's environment ('fixture') can be\n implemented by overriding the 'setUp' and 'tearDown' methods respectively.\n\n If it is necessary to override the __init__ method, the base class\n __init__ method must always be called. It is important that subclasses\n should not change the signature of their __init__ method, since instances\n of the classes are instantiated automatically by parts of the framework\n in order to be run.\n\n When subclassing TestCase, you can set these attributes:\n * failureException: determines which exception will be raised when\n the instance's assertion methods fail; test methods raising this\n exception will be deemed to have 'failed' rather than 'errored'.\n * longMessage: determines whether long messages (including repr of\n objects used in assert methods) will be printed on failure in *addition*\n to any explicit message passed.\n * maxDiff: sets the maximum length of a diff in failure messages\n by assert methods using difflib. It is looked up as an instance\n attribute so can be configured by individual tests if required.\n \"\"\"\n\n failureException = AssertionError\n\n longMessage = True\n\n maxDiff = 80*8\n\n # If a string is longer than _diffThreshold, use normal comparison instead\n # of difflib. See #11763.\n _diffThreshold = 2**16\n\n # Attribute used by TestSuite for classSetUp\n\n _classSetupFailed = False\n\n def __init__(self, methodName='runTest'):\n \"\"\"Create an instance of the class that will use the named test\n method when executed. Raises a ValueError if the instance does\n not have a method with the specified name.\n \"\"\"\n self._testMethodName = methodName\n self._outcomeForDoCleanups = None\n self._testMethodDoc = 'No test'\n try:\n testMethod = getattr(self, methodName)\n except AttributeError:\n if methodName != 'runTest':\n # we allow instantiation with no explicit method name\n # but not an *incorrect* or missing method name\n raise ValueError(\"no such test method in %s: %s\" %\n (self.__class__, methodName))\n else:\n self._testMethodDoc = testMethod.__doc__\n self._cleanups = []\n\n # Map types to custom assertEqual functions that will compare\n # instances of said type in more detail to generate a more useful\n # error message.\n self._type_equality_funcs = {}\n self.addTypeEqualityFunc(dict, 'assertDictEqual')\n self.addTypeEqualityFunc(list, 'assertListEqual')\n self.addTypeEqualityFunc(tuple, 'assertTupleEqual')\n self.addTypeEqualityFunc(set, 'assertSetEqual')\n self.addTypeEqualityFunc(frozenset, 'assertSetEqual')\n self.addTypeEqualityFunc(str, 'assertMultiLineEqual')\n\n def addTypeEqualityFunc(self, typeobj, function):\n \"\"\"Add a type specific assertEqual style function to compare a type.\n\n This method is for use by TestCase subclasses that need to register\n their own type equality functions to provide nicer error messages.\n\n Args:\n typeobj: The data type to call this function on when both values\n are of the same type in assertEqual().\n function: The callable taking two arguments and an optional\n msg= argument that raises self.failureException with a\n useful error message when the two arguments are not equal.\n \"\"\"\n self._type_equality_funcs[typeobj] = function\n\n def addCleanup(self, function, *args, **kwargs):\n \"\"\"Add a function, with arguments, to be called when the test is\n completed. Functions added are called on a LIFO basis and are\n called after tearDown on test failure or success.\n\n Cleanup items are called even if setUp fails (unlike tearDown).\"\"\"\n self._cleanups.append((function, args, kwargs))\n\n def setUp(self):\n \"Hook method for setting up the test fixture before exercising it.\"\n pass\n\n def tearDown(self):\n \"Hook method for deconstructing the test fixture after testing it.\"\n pass\n\n @classmethod\n def setUpClass(cls):\n \"Hook method for setting up class fixture before running tests in the class.\"\n\n @classmethod\n def tearDownClass(cls):\n \"Hook method for deconstructing the class fixture after running all tests in the class.\"\n\n def countTestCases(self):\n return 1\n\n def defaultTestResult(self):\n return result.TestResult()\n\n def shortDescription(self):\n \"\"\"Returns a one-line description of the test, or None if no\n description has been provided.\n\n The default implementation of this method returns the first line of\n the specified test method's docstring.\n \"\"\"\n doc = self._testMethodDoc\n return doc and doc.split(\"\\n\")[0].strip() or None\n\n\n def id(self):\n return \"%s.%s\" % (strclass(self.__class__), self._testMethodName)\n\n def __eq__(self, other):\n if type(self) is not type(other):\n return NotImplemented\n\n return self._testMethodName == other._testMethodName\n\n def __hash__(self):\n return hash((type(self), self._testMethodName))\n\n def __str__(self):\n return \"%s (%s)\" % (self._testMethodName, strclass(self.__class__))\n\n def __repr__(self):\n return \"<%s testMethod=%s>\" % \\\n (strclass(self.__class__), self._testMethodName)\n\n def _addSkip(self, result, reason):\n addSkip = getattr(result, 'addSkip', None)\n if addSkip is not None:\n addSkip(self, reason)\n else:\n warnings.warn(\"TestResult has no addSkip method, skips not reported\",\n RuntimeWarning, 2)\n result.addSuccess(self)\n\n def _executeTestPart(self, function, outcome, isTest=False):\n try:\n function()\n except KeyboardInterrupt:\n raise\n except SkipTest as e:\n outcome.success = False\n outcome.skipped = str(e)\n except _UnexpectedSuccess:\n exc_info = sys.exc_info()\n outcome.success = False\n if isTest:\n outcome.unexpectedSuccess = exc_info\n else:\n outcome.errors.append(exc_info)\n except _ExpectedFailure:\n outcome.success = False\n exc_info = sys.exc_info()\n if isTest:\n outcome.expectedFailure = exc_info\n else:\n outcome.errors.append(exc_info)\n except self.failureException:\n outcome.success = False\n outcome.failures.append(sys.exc_info())\n exc_info = sys.exc_info()\n except:\n outcome.success = False\n outcome.errors.append(sys.exc_info())\n\n def run(self, result=None):\n orig_result = result\n if result is None:\n result = self.defaultTestResult()\n startTestRun = getattr(result, 'startTestRun', None)\n if startTestRun is not None:\n startTestRun()\n\n result.startTest(self)\n\n testMethod = getattr(self, self._testMethodName)\n if (getattr(self.__class__, \"__unittest_skip__\", False) or\n getattr(testMethod, \"__unittest_skip__\", False)):\n # If the class or method was skipped.\n try:\n skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')\n or getattr(testMethod, '__unittest_skip_why__', ''))\n self._addSkip(result, skip_why)\n finally:\n result.stopTest(self)\n return\n try:\n outcome = _Outcome()\n self._outcomeForDoCleanups = outcome\n\n self._executeTestPart(self.setUp, outcome)\n if outcome.success:\n self._executeTestPart(testMethod, outcome, isTest=True)\n self._executeTestPart(self.tearDown, outcome)\n\n self.doCleanups()\n if outcome.success:\n result.addSuccess(self)\n else:\n if outcome.skipped is not None:\n self._addSkip(result, outcome.skipped)\n for exc_info in outcome.errors:\n result.addError(self, exc_info)\n for exc_info in outcome.failures:\n result.addFailure(self, exc_info)\n if outcome.unexpectedSuccess is not None:\n addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)\n if addUnexpectedSuccess is not None:\n addUnexpectedSuccess(self)\n else:\n warnings.warn(\"TestResult has no addUnexpectedSuccess method, reporting as failures\",\n RuntimeWarning)\n result.addFailure(self, outcome.unexpectedSuccess)\n\n if outcome.expectedFailure is not None:\n addExpectedFailure = getattr(result, 'addExpectedFailure', None)\n if addExpectedFailure is not None:\n addExpectedFailure(self, outcome.expectedFailure)\n else:\n warnings.warn(\"TestResult has no addExpectedFailure method, reporting as passes\",\n RuntimeWarning)\n result.addSuccess(self)\n return result\n finally:\n result.stopTest(self)\n if orig_result is None:\n stopTestRun = getattr(result, 'stopTestRun', None)\n if stopTestRun is not None:\n stopTestRun()\n\n def doCleanups(self):\n \"\"\"Execute all cleanup functions. Normally called for you after\n tearDown.\"\"\"\n outcome = self._outcomeForDoCleanups or _Outcome()\n while self._cleanups:\n function, args, kwargs = self._cleanups.pop()\n part = lambda: function(*args, **kwargs)\n self._executeTestPart(part, outcome)\n\n # return this for backwards compatibility\n # even though we no longer us it internally\n return outcome.success\n\n def __call__(self, *args, **kwds):\n return self.run(*args, **kwds)\n\n def debug(self):\n \"\"\"Run the test without collecting errors in a TestResult\"\"\"\n self.setUp()\n getattr(self, self._testMethodName)()\n self.tearDown()\n while self._cleanups:\n function, args, kwargs = self._cleanups.pop(-1)\n function(*args, **kwargs)\n\n def skipTest(self, reason):\n \"\"\"Skip this test.\"\"\"\n raise SkipTest(reason)\n\n def fail(self, msg=None):\n \"\"\"Fail immediately, with the given message.\"\"\"\n raise self.failureException(msg)\n\n def assertFalse(self, expr, msg=None):\n \"\"\"Check that the expression is false.\"\"\"\n if expr:\n msg = self._formatMessage(msg, \"%s is not false\" % safe_repr(expr))\n raise self.failureException(msg)\n\n def assertTrue(self, expr, msg=None):\n \"\"\"Check that the expression is true.\"\"\"\n if not expr:\n msg = self._formatMessage(msg, \"%s is not true\" % safe_repr(expr))\n raise self.failureException(msg)\n\n def _formatMessage(self, msg, standardMsg):\n \"\"\"Honour the longMessage attribute when generating failure messages.\n If longMessage is False this means:\n * Use only an explicit message if it is provided\n * Otherwise use the standard message for the assert\n\n If longMessage is True:\n * Use the standard message\n * If an explicit message is provided, plus ' : ' and the explicit message\n \"\"\"\n if not self.longMessage:\n return msg or standardMsg\n if msg is None:\n return standardMsg\n try:\n # don't switch to '{}' formatting in Python 2.X\n # it changes the way unicode input is handled\n return '%s : %s' % (standardMsg, msg)\n except UnicodeDecodeError:\n return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))\n\n def assertRaises(self, excClass, callableObj=None, *args, **kwargs):\n \"\"\"Fail unless an exception of class excClass is raised\n by callableObj when invoked with arguments args and keyword\n arguments kwargs. If a different type of exception is\n raised, it will not be caught, and the test case will be\n deemed to have suffered an error, exactly as for an\n unexpected exception.\n\n If called with callableObj omitted or None, will return a\n context object used like this::\n\n with self.assertRaises(SomeException):\n do_something()\n\n An optional keyword argument 'msg' can be provided when assertRaises\n is used as a context object.\n\n The context manager keeps a reference to the exception as\n the 'exception' attribute. This allows you to inspect the\n exception after the assertion::\n\n with self.assertRaises(SomeException) as cm:\n do_something()\n the_exception = cm.exception\n self.assertEqual(the_exception.error_code, 3)\n \"\"\"\n context = _AssertRaisesContext(excClass, self, callableObj)\n return context.handle('assertRaises', callableObj, args, kwargs)\n\n def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):\n \"\"\"Fail unless a warning of class warnClass is triggered\n by callable_obj when invoked with arguments args and keyword\n arguments kwargs. If a different type of warning is\n triggered, it will not be handled: depending on the other\n warning filtering rules in effect, it might be silenced, printed\n out, or raised as an exception.\n\n If called with callable_obj omitted or None, will return a\n context object used like this::\n\n with self.assertWarns(SomeWarning):\n do_something()\n\n An optional keyword argument 'msg' can be provided when assertWarns\n is used as a context object.\n\n The context manager keeps a reference to the first matching\n warning as the 'warning' attribute; similarly, the 'filename'\n and 'lineno' attributes give you information about the line\n of Python code from which the warning was triggered.\n This allows you to inspect the warning after the assertion::\n\n with self.assertWarns(SomeWarning) as cm:\n do_something()\n the_warning = cm.warning\n self.assertEqual(the_warning.some_attribute, 147)\n \"\"\"\n context = _AssertWarnsContext(expected_warning, self, callable_obj)\n return context.handle('assertWarns', callable_obj, args, kwargs)\n\n def _getAssertEqualityFunc(self, first, second):\n \"\"\"Get a detailed comparison function for the types of the two args.\n\n Returns: A callable accepting (first, second, msg=None) that will\n raise a failure exception if first != second with a useful human\n readable error message for those types.\n \"\"\"\n #\n # NOTE(gregory.p.smith): I considered isinstance(first, type(second))\n # and vice versa. I opted for the conservative approach in case\n # subclasses are not intended to be compared in detail to their super\n # class instances using a type equality func. This means testing\n # subtypes won't automagically use the detailed comparison. Callers\n # should use their type specific assertSpamEqual method to compare\n # subclasses if the detailed comparison is desired and appropriate.\n # See the discussion in http://bugs.python.org/issue2578.\n #\n if type(first) is type(second):\n asserter = self._type_equality_funcs.get(type(first))\n if asserter is not None:\n if isinstance(asserter, str):\n asserter = getattr(self, asserter)\n return asserter\n\n return self._baseAssertEqual\n\n def _baseAssertEqual(self, first, second, msg=None):\n \"\"\"The default assertEqual implementation, not type specific.\"\"\"\n if not first == second:\n standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))\n msg = self._formatMessage(msg, standardMsg)\n raise self.failureException(msg)\n\n def assertEqual(self, first, second, msg=None):\n \"\"\"Fail if the two objects are unequal as determined by the '=='\n operator.\n \"\"\"\n assertion_func = self._getAssertEqualityFunc(first, second)\n assertion_func(first, second, msg=msg)\n\n def assertNotEqual(self, first, second, msg=None):\n \"\"\"Fail if the two objects are equal as determined by the '!='\n operator.\n \"\"\"\n if not first != second:\n msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),\n safe_repr(second)))\n raise self.failureException(msg)\n\n def assertAlmostEqual(self, first, second, places=None, msg=None,\n delta=None):\n \"\"\"Fail if the two objects are unequal as determined by their\n difference rounded to the given number of decimal places\n (default 7) and comparing to zero, or by comparing that the\n between the two objects is more than the given delta.\n\n Note that decimal places (from zero) are usually not the same\n as significant digits (measured from the most signficant digit).\n\n If the two objects compare equal then they will automatically\n compare almost equal.\n \"\"\"\n if first == second:\n # shortcut\n return\n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n\n if delta is not None:\n if abs(first - second) <= delta:\n return\n\n standardMsg = '%s != %s within %s delta' % (safe_repr(first),\n safe_repr(second),\n safe_repr(delta))\n else:\n if places is None:\n places = 7\n\n if round(abs(second-first), places) == 0:\n return\n\n standardMsg = '%s != %s within %r places' % (safe_repr(first),\n safe_repr(second),\n places)\n msg = self._formatMessage(msg, standardMsg)\n raise self.failureException(msg)\n\n def assertNotAlmostEqual(self, first, second, places=None, msg=None,\n delta=None):\n \"\"\"Fail if the two objects are equal as determined by their\n difference rounded to the given number of decimal places\n (default 7) and comparing to zero, or by comparing that the\n between the two objects is less than the given delta.\n\n Note that decimal places (from zero) are usually not the same\n as significant digits (measured from the most signficant digit).\n\n Objects that are equal automatically fail.\n \"\"\"\n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n if delta is not None:\n if not (first == second) and abs(first - second) > delta:\n return\n standardMsg = '%s == %s within %s delta' % (safe_repr(first),\n safe_repr(second),\n safe_repr(delta))\n else:\n if places is None:\n places = 7\n if not (first == second) and round(abs(second-first), places) != 0:\n return\n standardMsg = '%s == %s within %r places' % (safe_repr(first),\n safe_repr(second),\n places)\n\n msg = self._formatMessage(msg, standardMsg)\n raise self.failureException(msg)\n\n\n def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):\n \"\"\"An equality assertion for ordered sequences (like lists and tuples).\n\n For the purposes of this function, a valid ordered sequence type is one\n which can be indexed, has a length, and has an equality operator.\n\n Args:\n seq1: The first sequence to compare.\n seq2: The second sequence to compare.\n seq_type: The expected datatype of the sequences, or None if no\n datatype should be enforced.\n msg: Optional message to use on failure instead of a list of\n differences.\n \"\"\"\n if seq_type is not None:\n seq_type_name = seq_type.__name__\n if not isinstance(seq1, seq_type):\n raise self.failureException('First sequence is not a %s: %s'\n % (seq_type_name, safe_repr(seq1)))\n if not isinstance(seq2, seq_type):\n raise self.failureException('Second sequence is not a %s: %s'\n % (seq_type_name, safe_repr(seq2)))\n else:\n seq_type_name = \"sequence\"\n\n differing = None\n try:\n len1 = len(seq1)\n except (TypeError, NotImplementedError):\n differing = 'First %s has no length. Non-sequence?' % (\n seq_type_name)\n\n if differing is None:\n try:\n len2 = len(seq2)\n except (TypeError, NotImplementedError):\n differing = 'Second %s has no length. Non-sequence?' % (\n seq_type_name)\n\n if differing is None:\n if seq1 == seq2:\n return\n\n seq1_repr = safe_repr(seq1)\n seq2_repr = safe_repr(seq2)\n if len(seq1_repr) > 30:\n seq1_repr = seq1_repr[:30] + '...'\n if len(seq2_repr) > 30:\n seq2_repr = seq2_repr[:30] + '...'\n elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)\n differing = '%ss differ: %s != %s\\n' % elements\n\n for i in range(min(len1, len2)):\n try:\n item1 = seq1[i]\n except (TypeError, IndexError, NotImplementedError):\n differing += ('\\nUnable to index element %d of first %s\\n' %\n (i, seq_type_name))\n break\n\n try:\n item2 = seq2[i]\n except (TypeError, IndexError, NotImplementedError):\n differing += ('\\nUnable to index element %d of second %s\\n' %\n (i, seq_type_name))\n break\n\n if item1 != item2:\n differing += ('\\nFirst differing element %d:\\n%s\\n%s\\n' %\n (i, item1, item2))\n break\n else:\n if (len1 == len2 and seq_type is None and\n type(seq1) != type(seq2)):\n # The sequences are the same, but have differing types.\n return\n\n if len1 > len2:\n differing += ('\\nFirst %s contains %d additional '\n 'elements.\\n' % (seq_type_name, len1 - len2))\n try:\n differing += ('First extra element %d:\\n%s\\n' %\n (len2, seq1[len2]))\n except (TypeError, IndexError, NotImplementedError):\n differing += ('Unable to index element %d '\n 'of first %s\\n' % (len2, seq_type_name))\n elif len1 < len2:\n differing += ('\\nSecond %s contains %d additional '\n 'elements.\\n' % (seq_type_name, len2 - len1))\n try:\n differing += ('First extra element %d:\\n%s\\n' %\n (len1, seq2[len1]))\n except (TypeError, IndexError, NotImplementedError):\n differing += ('Unable to index element %d '\n 'of second %s\\n' % (len1, seq_type_name))\n standardMsg = differing\n diffMsg = '\\n' + '\\n'.join(\n difflib.ndiff(pprint.pformat(seq1).splitlines(),\n pprint.pformat(seq2).splitlines()))\n\n standardMsg = self._truncateMessage(standardMsg, diffMsg)\n msg = self._formatMessage(msg, standardMsg)\n self.fail(msg)\n\n def _truncateMessage(self, message, diff):\n max_diff = self.maxDiff\n if max_diff is None or len(diff) <= max_diff:\n return message + diff\n return message + (DIFF_OMITTED % len(diff))\n\n def assertListEqual(self, list1, list2, msg=None):\n \"\"\"A list-specific equality assertion.\n\n Args:\n list1: The first list to compare.\n list2: The second list to compare.\n msg: Optional message to use on failure instead of a list of\n differences.\n\n \"\"\"\n self.assertSequenceEqual(list1, list2, msg, seq_type=list)\n\n def assertTupleEqual(self, tuple1, tuple2, msg=None):\n \"\"\"A tuple-specific equality assertion.\n\n Args:\n tuple1: The first tuple to compare.\n tuple2: The second tuple to compare.\n msg: Optional message to use on failure instead of a list of\n differences.\n \"\"\"\n self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)\n\n def assertSetEqual(self, set1, set2, msg=None):\n \"\"\"A set-specific equality assertion.\n\n Args:\n set1: The first set to compare.\n set2: The second set to compare.\n msg: Optional message to use on failure instead of a list of\n differences.\n\n assertSetEqual uses ducktyping to support different types of sets, and\n is optimized for sets specifically (parameters must support a\n difference method).\n \"\"\"\n try:\n difference1 = set1.difference(set2)\n except TypeError as e:\n self.fail('invalid type when attempting set difference: %s' % e)\n except AttributeError as e:\n self.fail('first argument does not support set difference: %s' % e)\n\n try:\n difference2 = set2.difference(set1)\n except TypeError as e:\n self.fail('invalid type when attempting set difference: %s' % e)\n except AttributeError as e:\n self.fail('second argument does not support set difference: %s' % e)\n\n if not (difference1 or difference2):\n return\n\n lines = []\n if difference1:\n lines.append('Items in the first set but not the second:')\n for item in difference1:\n lines.append(repr(item))\n if difference2:\n lines.append('Items in the second set but not the first:')\n for item in difference2:\n lines.append(repr(item))\n\n standardMsg = '\\n'.join(lines)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertIn(self, member, container, msg=None):\n \"\"\"Just like self.assertTrue(a in b), but with a nicer default message.\"\"\"\n if member not in container:\n standardMsg = '%s not found in %s' % (safe_repr(member),\n safe_repr(container))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertNotIn(self, member, container, msg=None):\n \"\"\"Just like self.assertTrue(a not in b), but with a nicer default message.\"\"\"\n if member in container:\n standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),\n safe_repr(container))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertIs(self, expr1, expr2, msg=None):\n \"\"\"Just like self.assertTrue(a is b), but with a nicer default message.\"\"\"\n if expr1 is not expr2:\n standardMsg = '%s is not %s' % (safe_repr(expr1),\n safe_repr(expr2))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertIsNot(self, expr1, expr2, msg=None):\n \"\"\"Just like self.assertTrue(a is not b), but with a nicer default message.\"\"\"\n if expr1 is expr2:\n standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertDictEqual(self, d1, d2, msg=None):\n self.assertIsInstance(d1, dict, 'First argument is not a dictionary')\n self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')\n\n if d1 != d2:\n standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))\n diff = ('\\n' + '\\n'.join(difflib.ndiff(\n pprint.pformat(d1).splitlines(),\n pprint.pformat(d2).splitlines())))\n standardMsg = self._truncateMessage(standardMsg, diff)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertDictContainsSubset(self, subset, dictionary, msg=None):\n \"\"\"Checks whether dictionary is a superset of subset.\"\"\"\n warnings.warn('assertDictContainsSubset is deprecated',\n DeprecationWarning)\n missing = []\n mismatched = []\n for key, value in subset.items():\n if key not in dictionary:\n missing.append(key)\n elif value != dictionary[key]:\n mismatched.append('%s, expected: %s, actual: %s' %\n (safe_repr(key), safe_repr(value),\n safe_repr(dictionary[key])))\n\n if not (missing or mismatched):\n return\n\n standardMsg = ''\n if missing:\n standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in\n missing)\n if mismatched:\n if standardMsg:\n standardMsg += '; '\n standardMsg += 'Mismatched values: %s' % ','.join(mismatched)\n\n self.fail(self._formatMessage(msg, standardMsg))\n\n\n def assertCountEqual(self, first, second, msg=None):\n \"\"\"An unordered sequence comparison asserting that the same elements,\n regardless of order. If the same element occurs more than once,\n it verifies that the elements occur the same number of times.\n\n self.assertEqual(Counter(list(first)),\n Counter(list(second)))\n\n Example:\n - [0, 1, 1] and [1, 0, 1] compare equal.\n - [0, 0, 1] and [0, 1] compare unequal.\n\n \"\"\"\n first_seq, second_seq = list(first), list(second)\n try:\n first = collections.Counter(first_seq)\n second = collections.Counter(second_seq)\n except TypeError:\n # Handle case with unhashable elements\n differences = _count_diff_all_purpose(first_seq, second_seq)\n else:\n if first == second:\n return\n differences = _count_diff_hashable(first_seq, second_seq)\n\n if differences:\n standardMsg = 'Element counts were not equal:\\n'\n lines = ['First has %d, Second has %d: %r' % diff for diff in differences]\n diffMsg = '\\n'.join(lines)\n standardMsg = self._truncateMessage(standardMsg, diffMsg)\n msg = self._formatMessage(msg, standardMsg)\n self.fail(msg)\n\n def assertMultiLineEqual(self, first, second, msg=None):\n \"\"\"Assert that two multi-line strings are equal.\"\"\"\n self.assertIsInstance(first, str, 'First argument is not a string')\n self.assertIsInstance(second, str, 'Second argument is not a string')\n\n if first != second:\n # don't use difflib if the strings are too long\n if (len(first) > self._diffThreshold or\n len(second) > self._diffThreshold):\n self._baseAssertEqual(first, second, msg)\n firstlines = first.splitlines(keepends=True)\n secondlines = second.splitlines(keepends=True)\n if len(firstlines) == 1 and first.strip('\\r\\n') == first:\n firstlines = [first + '\\n']\n secondlines = [second + '\\n']\n standardMsg = '%s != %s' % (safe_repr(first, True),\n safe_repr(second, True))\n diff = '\\n' + ''.join(difflib.ndiff(firstlines, secondlines))\n standardMsg = self._truncateMessage(standardMsg, diff)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertLess(self, a, b, msg=None):\n \"\"\"Just like self.assertTrue(a < b), but with a nicer default message.\"\"\"\n if not a < b:\n standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertLessEqual(self, a, b, msg=None):\n \"\"\"Just like self.assertTrue(a <= b), but with a nicer default message.\"\"\"\n if not a <= b:\n standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertGreater(self, a, b, msg=None):\n \"\"\"Just like self.assertTrue(a > b), but with a nicer default message.\"\"\"\n if not a > b:\n standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertGreaterEqual(self, a, b, msg=None):\n \"\"\"Just like self.assertTrue(a >= b), but with a nicer default message.\"\"\"\n if not a >= b:\n standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertIsNone(self, obj, msg=None):\n \"\"\"Same as self.assertTrue(obj is None), with a nicer default message.\"\"\"\n if obj is not None:\n standardMsg = '%s is not None' % (safe_repr(obj),)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertIsNotNone(self, obj, msg=None):\n \"\"\"Included for symmetry with assertIsNone.\"\"\"\n if obj is None:\n standardMsg = 'unexpectedly None'\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertIsInstance(self, obj, cls, msg=None):\n \"\"\"Same as self.assertTrue(isinstance(obj, cls)), with a nicer\n default message.\"\"\"\n if not isinstance(obj, cls):\n standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertNotIsInstance(self, obj, cls, msg=None):\n \"\"\"Included for symmetry with assertIsInstance.\"\"\"\n if isinstance(obj, cls):\n standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)\n self.fail(self._formatMessage(msg, standardMsg))\n\n def assertRaisesRegex(self, expected_exception, expected_regex,\n callable_obj=None, *args, **kwargs):\n \"\"\"Asserts that the message in a raised exception matches a regex.\n\n Args:\n expected_exception: Exception class expected to be raised.\n expected_regex: Regex (re pattern object or string) expected\n to be found in error message.\n callable_obj: Function to be called.\n msg: Optional message used in case of failure. Can only be used\n when assertRaisesRegex is used as a context manager.\n args: Extra args.\n kwargs: Extra kwargs.\n \"\"\"\n context = _AssertRaisesContext(expected_exception, self, callable_obj,\n expected_regex)\n\n return context.handle('assertRaisesRegex', callable_obj, args, kwargs)\n\n def assertWarnsRegex(self, expected_warning, expected_regex,\n callable_obj=None, *args, **kwargs):\n \"\"\"Asserts that the message in a triggered warning matches a regexp.\n Basic functioning is similar to assertWarns() with the addition\n that only warnings whose messages also match the regular expression\n are considered successful matches.\n\n Args:\n expected_warning: Warning class expected to be triggered.\n expected_regex: Regex (re pattern object or string) expected\n to be found in error message.\n callable_obj: Function to be called.\n msg: Optional message used in case of failure. Can only be used\n when assertWarnsRegex is used as a context manager.\n args: Extra args.\n kwargs: Extra kwargs.\n \"\"\"\n context = _AssertWarnsContext(expected_warning, self, callable_obj,\n expected_regex)\n return context.handle('assertWarnsRegex', callable_obj, args, kwargs)\n\n def assertRegex(self, text, expected_regex, msg=None):\n \"\"\"Fail the test unless the text matches the regular expression.\"\"\"\n if isinstance(expected_regex, (str, bytes)):\n assert expected_regex, \"expected_regex must not be empty.\"\n expected_regex = re.compile(expected_regex)\n if not expected_regex.search(text):\n msg = msg or \"Regex didn't match\"\n msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)\n raise self.failureException(msg)\n\n def assertNotRegex(self, text, unexpected_regex, msg=None):\n \"\"\"Fail the test if the text matches the regular expression.\"\"\"\n if isinstance(unexpected_regex, (str, bytes)):\n unexpected_regex = re.compile(unexpected_regex)\n match = unexpected_regex.search(text)\n if match:\n msg = msg or \"Regex matched\"\n msg = '%s: %r matches %r in %r' % (msg,\n text[match.start():match.end()],\n unexpected_regex.pattern,\n text)\n raise self.failureException(msg)\n\n\n def _deprecate(original_func):\n def deprecated_func(*args, **kwargs):\n warnings.warn(\n 'Please use {0} instead.'.format(original_func.__name__),\n DeprecationWarning, 2)\n return original_func(*args, **kwargs)\n return deprecated_func\n\n # see #9424\n failUnlessEqual = assertEquals = _deprecate(assertEqual)\n failIfEqual = assertNotEquals = _deprecate(assertNotEqual)\n failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)\n failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)\n failUnless = assert_ = _deprecate(assertTrue)\n failUnlessRaises = _deprecate(assertRaises)\n failIf = _deprecate(assertFalse)\n assertRaisesRegexp = _deprecate(assertRaisesRegex)\n assertRegexpMatches = _deprecate(assertRegex)\n\n\n\nclass FunctionTestCase(TestCase):\n \"\"\"A test case that wraps a test function.\n\n This is useful for slipping pre-existing test functions into the\n unittest framework. Optionally, set-up and tidy-up functions can be\n supplied. As with TestCase, the tidy-up ('tearDown') function will\n always be called if the set-up ('setUp') function ran successfully.\n \"\"\"\n\n def __init__(self, testFunc, setUp=None, tearDown=None, description=None):\n super(FunctionTestCase, self).__init__()\n self._setUpFunc = setUp\n self._tearDownFunc = tearDown\n self._testFunc = testFunc\n self._description = description\n\n def setUp(self):\n if self._setUpFunc is not None:\n self._setUpFunc()\n\n def tearDown(self):\n if self._tearDownFunc is not None:\n self._tearDownFunc()\n\n def runTest(self):\n self._testFunc()\n\n def id(self):\n return self._testFunc.__name__\n\n def __eq__(self, other):\n if not isinstance(other, self.__class__):\n return NotImplemented\n\n return self._setUpFunc == other._setUpFunc and \\\n self._tearDownFunc == other._tearDownFunc and \\\n self._testFunc == other._testFunc and \\\n self._description == other._description\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash((type(self), self._setUpFunc, self._tearDownFunc,\n self._testFunc, self._description))\n\n def __str__(self):\n return \"%s (%s)\" % (strclass(self.__class__),\n self._testFunc.__name__)\n\n def __repr__(self):\n return \"<%s tec=%s>\" % (strclass(self.__class__),\n self._testFunc)\n\n def shortDescription(self):\n if self._description is not None:\n return self._description\n doc = self._testFunc.__doc__\n return doc and doc.split(\"\\n\")[0].strip() or None\n"},"license":{"kind":"string","value":"gpl-3.0"}}},{"rowIdx":476125,"cells":{"repo_name":{"kind":"string","value":"jbassen/edx-platform"},"path":{"kind":"string","value":"common/test/acceptance/tests/lms/test_lms_edxnotes.py"},"copies":{"kind":"string","value":"84"},"size":{"kind":"string","value":"44359"},"content":{"kind":"string","value":"\"\"\"\nTest LMS Notes\n\"\"\"\nfrom uuid import uuid4\nfrom datetime import datetime\nfrom nose.plugins.attrib import attr\nfrom ..helpers import UniqueCourseTest\nfrom ...fixtures.course import CourseFixture, XBlockFixtureDesc\nfrom ...pages.lms.auto_auth import AutoAuthPage\nfrom ...pages.lms.course_nav import CourseNavPage\nfrom ...pages.lms.courseware import CoursewarePage\nfrom ...pages.lms.edxnotes import EdxNotesUnitPage, EdxNotesPage, EdxNotesPageNoContent\nfrom ...fixtures.edxnotes import EdxNotesFixture, Note, Range\nfrom ..helpers import EventsTestMixin\n\n\nclass EdxNotesTestMixin(UniqueCourseTest):\n \"\"\"\n Creates a course with initial data and contains useful helper methods.\n \"\"\"\n def setUp(self):\n \"\"\"\n Initialize pages and install a course fixture.\n \"\"\"\n super(EdxNotesTestMixin, self).setUp()\n self.courseware_page = CoursewarePage(self.browser, self.course_id)\n self.course_nav = CourseNavPage(self.browser)\n self.note_unit_page = EdxNotesUnitPage(self.browser, self.course_id)\n self.notes_page = EdxNotesPage(self.browser, self.course_id)\n\n self.username = str(uuid4().hex)[:5]\n self.email = \"{}@email.com\".format(self.username)\n\n self.selector = \"annotate-id\"\n self.edxnotes_fixture = EdxNotesFixture()\n self.course_fixture = CourseFixture(\n self.course_info[\"org\"], self.course_info[\"number\"],\n self.course_info[\"run\"], self.course_info[\"display_name\"]\n )\n\n self.course_fixture.add_advanced_settings({\n u\"edxnotes\": {u\"value\": True}\n })\n\n self.course_fixture.add_children(\n XBlockFixtureDesc(\"chapter\", \"Test Section 1\").add_children(\n XBlockFixtureDesc(\"sequential\", \"Test Subsection 1\").add_children(\n XBlockFixtureDesc(\"vertical\", \"Test Unit 1\").add_children(\n XBlockFixtureDesc(\n \"html\",\n \"Test HTML 1\",\n data=\"\"\"\n
Annotate this text!
\n
Annotate this text
\n \"\"\".format(self.selector)\n ),\n XBlockFixtureDesc(\n \"html\",\n \"Test HTML 2\",\n data=\"\"\"
Annotate this text!
\"\"\".format(self.selector)\n ),\n ),\n XBlockFixtureDesc(\"vertical\", \"Test Unit 2\").add_children(\n XBlockFixtureDesc(\n \"html\",\n \"Test HTML 3\",\n data=\"\"\"
Annotate this text!
\"\"\".format(self.selector)\n ),\n ),\n ),\n XBlockFixtureDesc(\"sequential\", \"Test Subsection 2\").add_children(\n XBlockFixtureDesc(\"vertical\", \"Test Unit 3\").add_children(\n XBlockFixtureDesc(\n \"html\",\n \"Test HTML 4\",\n data=\"\"\"\n
Annotate this text!
\n \"\"\".format(self.selector)\n ),\n ),\n ),\n ),\n XBlockFixtureDesc(\"chapter\", \"Test Section 2\").add_children(\n XBlockFixtureDesc(\"sequential\", \"Test Subsection 3\").add_children(\n XBlockFixtureDesc(\"vertical\", \"Test Unit 4\").add_children(\n XBlockFixtureDesc(\n \"html\",\n \"Test HTML 5\",\n data=\"\"\"\n
Annotate this text!
\n \"\"\".format(self.selector)\n ),\n XBlockFixtureDesc(\n \"html\",\n \"Test HTML 6\",\n data=\"\"\"
Annotate this text!
\"\"\".format(self.selector)\n ),\n ),\n ),\n )).install()\n\n self.addCleanup(self.edxnotes_fixture.cleanup)\n\n AutoAuthPage(self.browser, username=self.username, email=self.email, course_id=self.course_id).visit()\n\n def _add_notes(self):\n xblocks = self.course_fixture.get_nested_xblocks(category=\"html\")\n notes_list = []\n for index, xblock in enumerate(xblocks):\n notes_list.append(\n Note(\n user=self.username,\n usage_id=xblock.locator,\n course_id=self.course_fixture._course_key,\n ranges=[Range(startOffset=index, endOffset=index + 5)]\n )\n )\n\n self.edxnotes_fixture.create_notes(notes_list)\n self.edxnotes_fixture.install()\n\n\n@attr('shard_4')\nclass EdxNotesDefaultInteractionsTest(EdxNotesTestMixin):\n \"\"\"\n Tests for creation, editing, deleting annotations inside annotatable components in LMS.\n \"\"\"\n def create_notes(self, components, offset=0):\n self.assertGreater(len(components), 0)\n index = offset\n for component in components:\n for note in component.create_note(\".{}\".format(self.selector)):\n note.text = \"TEST TEXT {}\".format(index)\n index += 1\n\n def edit_notes(self, components, offset=0):\n self.assertGreater(len(components), 0)\n index = offset\n for component in components:\n self.assertGreater(len(component.notes), 0)\n for note in component.edit_note():\n note.text = \"TEST TEXT {}\".format(index)\n index += 1\n\n def edit_tags_in_notes(self, components, tags):\n self.assertGreater(len(components), 0)\n index = 0\n for component in components:\n self.assertGreater(len(component.notes), 0)\n for note in component.edit_note():\n note.tags = tags[index]\n index += 1\n self.assertEqual(index, len(tags), \"Number of supplied tags did not match components\")\n\n def remove_notes(self, components):\n self.assertGreater(len(components), 0)\n for component in components:\n self.assertGreater(len(component.notes), 0)\n component.remove_note()\n\n def assert_notes_are_removed(self, components):\n for component in components:\n self.assertEqual(0, len(component.notes))\n\n def assert_text_in_notes(self, notes):\n actual = [note.text for note in notes]\n expected = [\"TEST TEXT {}\".format(i) for i in xrange(len(notes))]\n self.assertEqual(expected, actual)\n\n def assert_tags_in_notes(self, notes, expected_tags):\n actual = [note.tags for note in notes]\n expected = [expected_tags[i] for i in xrange(len(notes))]\n self.assertEqual(expected, actual)\n\n def test_can_create_notes(self):\n \"\"\"\n Scenario: User can create notes.\n Given I have a course with 3 annotatable components\n And I open the unit with 2 annotatable components\n When I add 2 notes for the first component and 1 note for the second\n Then I see that notes were correctly created\n When I change sequential position to \"2\"\n And I add note for the annotatable component on the page\n Then I see that note was correctly created\n When I refresh the page\n Then I see that note was correctly stored\n When I change sequential position to \"1\"\n Then I see that notes were correctly stored on the page\n \"\"\"\n self.note_unit_page.visit()\n\n components = self.note_unit_page.components\n self.create_notes(components)\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n self.course_nav.go_to_sequential_position(2)\n components = self.note_unit_page.components\n self.create_notes(components)\n\n components = self.note_unit_page.refresh()\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n self.course_nav.go_to_sequential_position(1)\n components = self.note_unit_page.components\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n def test_can_edit_notes(self):\n \"\"\"\n Scenario: User can edit notes.\n Given I have a course with 3 components with notes\n And I open the unit with 2 annotatable components\n When I change text in the notes\n Then I see that notes were correctly changed\n When I change sequential position to \"2\"\n And I change the note on the page\n Then I see that note was correctly changed\n When I refresh the page\n Then I see that edited note was correctly stored\n When I change sequential position to \"1\"\n Then I see that edited notes were correctly stored on the page\n \"\"\"\n self._add_notes()\n self.note_unit_page.visit()\n\n components = self.note_unit_page.components\n self.edit_notes(components)\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n self.course_nav.go_to_sequential_position(2)\n components = self.note_unit_page.components\n self.edit_notes(components)\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n components = self.note_unit_page.refresh()\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n self.course_nav.go_to_sequential_position(1)\n components = self.note_unit_page.components\n self.assert_text_in_notes(self.note_unit_page.notes)\n\n def test_can_delete_notes(self):\n \"\"\"\n Scenario: User can delete notes.\n Given I have a course with 3 components with notes\n And I open the unit with 2 annotatable components\n When I remove all notes on the page\n Then I do not see any notes on the page\n When I change sequential position to \"2\"\n And I remove all notes on the page\n Then I do not see any notes on the page\n When I refresh the page\n Then I do not see any notes on the page\n When I change sequential position to \"1\"\n Then I do not see any notes on the page\n \"\"\"\n self._add_notes()\n self.note_unit_page.visit()\n\n components = self.note_unit_page.components\n self.remove_notes(components)\n self.assert_notes_are_removed(components)\n\n self.course_nav.go_to_sequential_position(2)\n components = self.note_unit_page.components\n self.remove_notes(components)\n self.assert_notes_are_removed(components)\n\n components = self.note_unit_page.refresh()\n self.assert_notes_are_removed(components)\n\n self.course_nav.go_to_sequential_position(1)\n components = self.note_unit_page.components\n self.assert_notes_are_removed(components)\n\n def test_can_create_note_with_tags(self):\n \"\"\"\n Scenario: a user of notes can define one with tags\n Given I have a course with 3 annotatable components\n And I open the unit with 2 annotatable components\n When I add a note with tags for the first component\n And I refresh the page\n Then I see that note was correctly stored with its tags\n \"\"\"\n self.note_unit_page.visit()\n\n components = self.note_unit_page.components\n for note in components[0].create_note(\".{}\".format(self.selector)):\n note.tags = [\"fruit\", \"tasty\"]\n\n self.note_unit_page.refresh()\n self.assertEqual([\"fruit\", \"tasty\"], self.note_unit_page.notes[0].tags)\n\n def test_can_change_tags(self):\n \"\"\"\n Scenario: a user of notes can edit tags on notes\n Given I have a course with 3 components with notes\n When I open the unit with 2 annotatable components\n And I edit tags on the notes for the 2 annotatable components\n Then I see that the tags were correctly changed\n And I again edit tags on the notes for the 2 annotatable components\n And I refresh the page\n Then I see that the tags were correctly changed\n \"\"\"\n self._add_notes()\n self.note_unit_page.visit()\n\n components = self.note_unit_page.components\n self.edit_tags_in_notes(components, [[\"hard\"], [\"apple\", \"pear\"]])\n self.assert_tags_in_notes(self.note_unit_page.notes, [[\"hard\"], [\"apple\", \"pear\"]])\n\n self.edit_tags_in_notes(components, [[], [\"avocado\"]])\n self.assert_tags_in_notes(self.note_unit_page.notes, [[], [\"avocado\"]])\n\n self.note_unit_page.refresh()\n self.assert_tags_in_notes(self.note_unit_page.notes, [[], [\"avocado\"]])\n\n def test_sr_labels(self):\n \"\"\"\n Scenario: screen reader labels exist for text and tags fields\n Given I have a course with 3 components with notes\n When I open the unit with 2 annotatable components\n And I open the editor for each note\n Then the text and tags fields both have screen reader labels\n \"\"\"\n self._add_notes()\n self.note_unit_page.visit()\n\n # First note is in the first annotatable component, will have field indexes 0 and 1.\n for note in self.note_unit_page.components[0].edit_note():\n self.assertTrue(note.has_sr_label(0, 0, \"Note\"))\n self.assertTrue(note.has_sr_label(1, 1, \"Tags (space-separated)\"))\n\n # Second note is in the second annotatable component, will have field indexes 2 and 3.\n for note in self.note_unit_page.components[1].edit_note():\n self.assertTrue(note.has_sr_label(0, 2, \"Note\"))\n self.assertTrue(note.has_sr_label(1, 3, \"Tags (space-separated)\"))\n\n\n@attr('shard_4')\nclass EdxNotesPageTest(EventsTestMixin, EdxNotesTestMixin):\n \"\"\"\n Tests for Notes page.\n \"\"\"\n def _add_notes(self, notes_list):\n self.edxnotes_fixture.create_notes(notes_list)\n self.edxnotes_fixture.install()\n\n def _add_default_notes(self, tags=None):\n \"\"\"\n Creates 5 test notes. If tags are not specified, will populate the notes with some test tag data.\n If tags are specified, they will be used for each of the 3 notes that have tags.\n \"\"\"\n xblocks = self.course_fixture.get_nested_xblocks(category=\"html\")\n # pylint: disable=attribute-defined-outside-init\n self.raw_note_list = [\n Note(\n usage_id=xblocks[4].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"First note\",\n quote=\"Annotate this text\",\n updated=datetime(2011, 1, 1, 1, 1, 1, 1).isoformat(),\n ),\n Note(\n usage_id=xblocks[2].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"\",\n quote=u\"Annotate this text\",\n updated=datetime(2012, 1, 1, 1, 1, 1, 1).isoformat(),\n tags=[\"Review\", \"cool\"] if tags is None else tags\n ),\n Note(\n usage_id=xblocks[0].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"Third note\",\n quote=\"Annotate this text\",\n updated=datetime(2013, 1, 1, 1, 1, 1, 1).isoformat(),\n ranges=[Range(startOffset=0, endOffset=18)],\n tags=[\"Cool\", \"TODO\"] if tags is None else tags\n ),\n Note(\n usage_id=xblocks[3].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"Fourth note\",\n quote=\"\",\n updated=datetime(2014, 1, 1, 1, 1, 1, 1).isoformat(),\n tags=[\"review\"] if tags is None else tags\n ),\n Note(\n usage_id=xblocks[1].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"Fifth note\",\n quote=\"Annotate this text\",\n updated=datetime(2015, 1, 1, 1, 1, 1, 1).isoformat()\n ),\n ]\n self._add_notes(self.raw_note_list)\n\n def assertNoteContent(self, item, text=None, quote=None, unit_name=None, time_updated=None, tags=None):\n \"\"\" Verifies the expected properties of the note. \"\"\"\n self.assertEqual(text, item.text)\n if item.quote is not None:\n self.assertIn(quote, item.quote)\n else:\n self.assertIsNone(quote)\n self.assertEqual(unit_name, item.unit_name)\n self.assertEqual(time_updated, item.time_updated)\n self.assertEqual(tags, item.tags)\n\n def assertChapterContent(self, item, title=None, subtitles=None):\n \"\"\"\n Verifies the expected title and subsection titles (subtitles) for the given chapter.\n \"\"\"\n self.assertEqual(item.title, title)\n self.assertEqual(item.subtitles, subtitles)\n\n def assertGroupContent(self, item, title=None, notes=None):\n \"\"\"\n Verifies the expected title and child notes for the given group.\n \"\"\"\n self.assertEqual(item.title, title)\n self.assertEqual(item.notes, notes)\n\n def assert_viewed_event(self, view=None):\n \"\"\"\n Verifies that the correct view event was captured for the Notes page.\n \"\"\"\n # There will always be an initial event for \"Recent Activity\" because that is the default view.\n # If view is something besides \"Recent Activity\", expect 2 events, with the second one being\n # the view name passed in.\n if view == 'Recent Activity':\n view = None\n actual_events = self.wait_for_events(\n event_filter={'event_type': 'edx.course.student_notes.notes_page_viewed'},\n number_of_matches=1 if view is None else 2\n )\n expected_events = [{'event': {'view': 'Recent Activity'}}]\n if view:\n expected_events.append({'event': {'view': view}})\n self.assert_events_match(expected_events, actual_events)\n\n def assert_unit_link_event(self, usage_id, view):\n \"\"\"\n Verifies that the correct used_unit_link event was captured for the Notes page.\n \"\"\"\n actual_events = self.wait_for_events(\n event_filter={'event_type': 'edx.course.student_notes.used_unit_link'},\n number_of_matches=1\n )\n expected_events = [\n {'event': {'component_usage_id': usage_id, 'view': view}}\n ]\n self.assert_events_match(expected_events, actual_events)\n\n def assert_search_event(self, search_string, number_of_results):\n \"\"\"\n Verifies that the correct searched event was captured for the Notes page.\n \"\"\"\n actual_events = self.wait_for_events(\n event_filter={'event_type': 'edx.course.student_notes.searched'},\n number_of_matches=1\n )\n expected_events = [\n {'event': {'search_string': search_string, 'number_of_results': number_of_results}}\n ]\n self.assert_events_match(expected_events, actual_events)\n\n def test_no_content(self):\n \"\"\"\n Scenario: User can see `No content` message.\n Given I have a course without notes\n When I open Notes page\n Then I see only \"You do not have any notes within the course.\" message\n \"\"\"\n notes_page_empty = EdxNotesPageNoContent(self.browser, self.course_id)\n notes_page_empty.visit()\n self.assertIn(\n \"You have not made any notes in this course yet. Other students in this course are using notes to:\",\n notes_page_empty.no_content_text)\n\n def test_recent_activity_view(self):\n \"\"\"\n Scenario: User can view all notes by recent activity.\n Given I have a course with 5 notes\n When I open Notes page\n Then I see 5 notes sorted by the updated date\n And I see correct content in the notes\n And an event has fired indicating that the Recent Activity view was selected\n \"\"\"\n self._add_default_notes()\n self.notes_page.visit()\n notes = self.notes_page.notes\n self.assertEqual(len(notes), 5)\n\n self.assertNoteContent(\n notes[0],\n quote=u\"Annotate this text\",\n text=u\"Fifth note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2015 at 01:01 UTC\"\n )\n\n self.assertNoteContent(\n notes[1],\n text=u\"Fourth note\",\n unit_name=\"Test Unit 3\",\n time_updated=\"Jan 01, 2014 at 01:01 UTC\",\n tags=[\"review\"]\n )\n\n self.assertNoteContent(\n notes[2],\n quote=\"Annotate this text\",\n text=u\"Third note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2013 at 01:01 UTC\",\n tags=[\"Cool\", \"TODO\"]\n )\n\n self.assertNoteContent(\n notes[3],\n quote=u\"Annotate this text\",\n unit_name=\"Test Unit 2\",\n time_updated=\"Jan 01, 2012 at 01:01 UTC\",\n tags=[\"Review\", \"cool\"]\n )\n\n self.assertNoteContent(\n notes[4],\n quote=u\"Annotate this text\",\n text=u\"First note\",\n unit_name=\"Test Unit 4\",\n time_updated=\"Jan 01, 2011 at 01:01 UTC\"\n )\n\n self.assert_viewed_event()\n\n def test_course_structure_view(self):\n \"\"\"\n Scenario: User can view all notes by location in Course.\n Given I have a course with 5 notes\n When I open Notes page\n And I switch to \"Location in Course\" view\n Then I see 2 groups, 3 sections and 5 notes\n And I see correct content in the notes and groups\n And an event has fired indicating that the Location in Course view was selected\n \"\"\"\n self._add_default_notes()\n self.notes_page.visit().switch_to_tab(\"structure\")\n\n notes = self.notes_page.notes\n groups = self.notes_page.chapter_groups\n sections = self.notes_page.subsection_groups\n self.assertEqual(len(notes), 5)\n self.assertEqual(len(groups), 2)\n self.assertEqual(len(sections), 3)\n\n self.assertChapterContent(\n groups[0],\n title=u\"Test Section 1\",\n subtitles=[u\"Test Subsection 1\", u\"Test Subsection 2\"]\n )\n\n self.assertGroupContent(\n sections[0],\n title=u\"Test Subsection 1\",\n notes=[u\"Fifth note\", u\"Third note\", None]\n )\n\n self.assertNoteContent(\n notes[0],\n quote=u\"Annotate this text\",\n text=u\"Fifth note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2015 at 01:01 UTC\"\n )\n\n self.assertNoteContent(\n notes[1],\n quote=u\"Annotate this text\",\n text=u\"Third note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2013 at 01:01 UTC\",\n tags=[\"Cool\", \"TODO\"]\n )\n\n self.assertNoteContent(\n notes[2],\n quote=u\"Annotate this text\",\n unit_name=\"Test Unit 2\",\n time_updated=\"Jan 01, 2012 at 01:01 UTC\",\n tags=[\"Review\", \"cool\"]\n )\n\n self.assertGroupContent(\n sections[1],\n title=u\"Test Subsection 2\",\n notes=[u\"Fourth note\"]\n )\n\n self.assertNoteContent(\n notes[3],\n text=u\"Fourth note\",\n unit_name=\"Test Unit 3\",\n time_updated=\"Jan 01, 2014 at 01:01 UTC\",\n tags=[\"review\"]\n )\n\n self.assertChapterContent(\n groups[1],\n title=u\"Test Section 2\",\n subtitles=[u\"Test Subsection 3\"],\n )\n\n self.assertGroupContent(\n sections[2],\n title=u\"Test Subsection 3\",\n notes=[u\"First note\"]\n )\n\n self.assertNoteContent(\n notes[4],\n quote=u\"Annotate this text\",\n text=u\"First note\",\n unit_name=\"Test Unit 4\",\n time_updated=\"Jan 01, 2011 at 01:01 UTC\"\n )\n\n self.assert_viewed_event('Location in Course')\n\n def test_tags_view(self):\n \"\"\"\n Scenario: User can view all notes by associated tags.\n Given I have a course with 5 notes and I am viewing the Notes page\n When I switch to the \"Tags\" view\n Then I see 4 tag groups\n And I see correct content in the notes and groups\n And an event has fired indicating that the Tags view was selected\n \"\"\"\n self._add_default_notes()\n self.notes_page.visit().switch_to_tab(\"tags\")\n\n notes = self.notes_page.notes\n groups = self.notes_page.tag_groups\n self.assertEqual(len(notes), 7)\n self.assertEqual(len(groups), 4)\n\n # Tag group \"cool\"\n self.assertGroupContent(\n groups[0],\n title=u\"cool (2)\",\n notes=[u\"Third note\", None]\n )\n\n self.assertNoteContent(\n notes[0],\n quote=u\"Annotate this text\",\n text=u\"Third note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2013 at 01:01 UTC\",\n tags=[\"Cool\", \"TODO\"]\n )\n\n self.assertNoteContent(\n notes[1],\n quote=u\"Annotate this text\",\n unit_name=\"Test Unit 2\",\n time_updated=\"Jan 01, 2012 at 01:01 UTC\",\n tags=[\"Review\", \"cool\"]\n )\n\n # Tag group \"review\"\n self.assertGroupContent(\n groups[1],\n title=u\"review (2)\",\n notes=[u\"Fourth note\", None]\n )\n\n self.assertNoteContent(\n notes[2],\n text=u\"Fourth note\",\n unit_name=\"Test Unit 3\",\n time_updated=\"Jan 01, 2014 at 01:01 UTC\",\n tags=[\"review\"]\n )\n\n self.assertNoteContent(\n notes[3],\n quote=u\"Annotate this text\",\n unit_name=\"Test Unit 2\",\n time_updated=\"Jan 01, 2012 at 01:01 UTC\",\n tags=[\"Review\", \"cool\"]\n )\n\n # Tag group \"todo\"\n self.assertGroupContent(\n groups[2],\n title=u\"todo (1)\",\n notes=[\"Third note\"]\n )\n\n self.assertNoteContent(\n notes[4],\n quote=u\"Annotate this text\",\n text=u\"Third note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2013 at 01:01 UTC\",\n tags=[\"Cool\", \"TODO\"]\n )\n\n # Notes with no tags\n self.assertGroupContent(\n groups[3],\n title=u\"[no tags] (2)\",\n notes=[\"Fifth note\", \"First note\"]\n )\n\n self.assertNoteContent(\n notes[5],\n quote=u\"Annotate this text\",\n text=u\"Fifth note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2015 at 01:01 UTC\"\n )\n\n self.assertNoteContent(\n notes[6],\n quote=u\"Annotate this text\",\n text=u\"First note\",\n unit_name=\"Test Unit 4\",\n time_updated=\"Jan 01, 2011 at 01:01 UTC\"\n )\n\n self.assert_viewed_event('Tags')\n\n def test_easy_access_from_notes_page(self):\n \"\"\"\n Scenario: Ensure that the link to the Unit works correctly.\n Given I have a course with 5 notes\n When I open Notes page\n And I click on the first unit link\n Then I see correct text on the unit page and a unit link event was fired\n When go back to the Notes page\n And I switch to \"Location in Course\" view\n And I click on the second unit link\n Then I see correct text on the unit page and a unit link event was fired\n When go back to the Notes page\n And I switch to \"Tags\" view\n And I click on the first unit link\n Then I see correct text on the unit page and a unit link event was fired\n When go back to the Notes page\n And I run the search with \"Fifth\" query\n And I click on the first unit link\n Then I see correct text on the unit page and a unit link event was fired\n \"\"\"\n def assert_page(note, usage_id, view):\n \"\"\" Verify that clicking on the unit link works properly. \"\"\"\n quote = note.quote\n note.go_to_unit()\n self.courseware_page.wait_for_page()\n self.assertIn(quote, self.courseware_page.xblock_component_html_content())\n self.assert_unit_link_event(usage_id, view)\n self.reset_event_tracking()\n\n self._add_default_notes()\n self.notes_page.visit()\n note = self.notes_page.notes[0]\n assert_page(note, self.raw_note_list[4]['usage_id'], \"Recent Activity\")\n\n self.notes_page.visit().switch_to_tab(\"structure\")\n note = self.notes_page.notes[1]\n assert_page(note, self.raw_note_list[2]['usage_id'], \"Location in Course\")\n\n self.notes_page.visit().switch_to_tab(\"tags\")\n note = self.notes_page.notes[0]\n assert_page(note, self.raw_note_list[2]['usage_id'], \"Tags\")\n\n self.notes_page.visit().search(\"Fifth\")\n note = self.notes_page.notes[0]\n assert_page(note, self.raw_note_list[4]['usage_id'], \"Search Results\")\n\n def test_search_behaves_correctly(self):\n \"\"\"\n Scenario: Searching behaves correctly.\n Given I have a course with 5 notes\n When I open Notes page\n When I run the search with \" \" query\n Then I see the following error message \"Please enter a term in the search field.\"\n And I do not see \"Search Results\" tab\n When I run the search with \"note\" query\n Then I see that error message disappears\n And I see that \"Search Results\" tab appears with 4 notes found\n And an event has fired indicating that the Search Results view was selected\n And an event has fired recording the search that was performed\n \"\"\"\n self._add_default_notes()\n self.notes_page.visit()\n # Run the search with whitespaces only\n self.notes_page.search(\" \")\n # Displays error message\n self.assertTrue(self.notes_page.is_error_visible)\n self.assertEqual(self.notes_page.error_text, u\"Please enter a term in the search field.\")\n # Search results tab does not appear\n self.assertNotIn(u\"Search Results\", self.notes_page.tabs)\n # Run the search with correct query\n self.notes_page.search(\"note\")\n # Error message disappears\n self.assertFalse(self.notes_page.is_error_visible)\n self.assertIn(u\"Search Results\", self.notes_page.tabs)\n notes = self.notes_page.notes\n self.assertEqual(len(notes), 4)\n\n self.assertNoteContent(\n notes[0],\n quote=u\"Annotate this text\",\n text=u\"Fifth note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2015 at 01:01 UTC\"\n )\n\n self.assertNoteContent(\n notes[1],\n text=u\"Fourth note\",\n unit_name=\"Test Unit 3\",\n time_updated=\"Jan 01, 2014 at 01:01 UTC\",\n tags=[\"review\"]\n )\n\n self.assertNoteContent(\n notes[2],\n quote=\"Annotate this text\",\n text=u\"Third note\",\n unit_name=\"Test Unit 1\",\n time_updated=\"Jan 01, 2013 at 01:01 UTC\",\n tags=[\"Cool\", \"TODO\"]\n )\n\n self.assertNoteContent(\n notes[3],\n quote=u\"Annotate this text\",\n text=u\"First note\",\n unit_name=\"Test Unit 4\",\n time_updated=\"Jan 01, 2011 at 01:01 UTC\"\n )\n\n self.assert_viewed_event('Search Results')\n self.assert_search_event('note', 4)\n\n def test_scroll_to_tag_recent_activity(self):\n \"\"\"\n Scenario: Can scroll to a tag group from the Recent Activity view (default view)\n Given I have a course with 5 notes and I open the Notes page\n When I click on a tag associated with a note\n Then the Tags view tab gets focus and I scroll to the section of notes associated with that tag\n \"\"\"\n self._add_default_notes([\"apple\", \"banana\", \"kiwi\", \"pear\", \"pumpkin\", \"squash\", \"zucchini\"])\n self.notes_page.visit()\n self._scroll_to_tag_and_verify(\"pear\", 3)\n\n def test_scroll_to_tag_course_structure(self):\n \"\"\"\n Scenario: Can scroll to a tag group from the Course Structure view\n Given I have a course with 5 notes and I open the Notes page and select the Course Structure view\n When I click on a tag associated with a note\n Then the Tags view tab gets focus and I scroll to the section of notes associated with that tag\n \"\"\"\n self._add_default_notes([\"apple\", \"banana\", \"kiwi\", \"pear\", \"pumpkin\", \"squash\", \"zucchini\"])\n self.notes_page.visit().switch_to_tab(\"structure\")\n self._scroll_to_tag_and_verify(\"squash\", 5)\n\n def test_scroll_to_tag_search(self):\n \"\"\"\n Scenario: Can scroll to a tag group from the Search Results view\n Given I have a course with 5 notes and I open the Notes page and perform a search\n Then the Search view tab opens and gets focus\n And when I click on a tag associated with a note\n Then the Tags view tab gets focus and I scroll to the section of notes associated with that tag\n \"\"\"\n self._add_default_notes([\"apple\", \"banana\", \"kiwi\", \"pear\", \"pumpkin\", \"squash\", \"zucchini\"])\n self.notes_page.visit().search(\"note\")\n self._scroll_to_tag_and_verify(\"pumpkin\", 4)\n\n def test_scroll_to_tag_from_tag_view(self):\n \"\"\"\n Scenario: Can scroll to a tag group from the Tags view\n Given I have a course with 5 notes and I open the Notes page and select the Tag view\n When I click on a tag associated with a note\n Then I scroll to the section of notes associated with that tag\n \"\"\"\n self._add_default_notes([\"apple\", \"banana\", \"kiwi\", \"pear\", \"pumpkin\", \"squash\", \"zucchini\"])\n self.notes_page.visit().switch_to_tab(\"tags\")\n self._scroll_to_tag_and_verify(\"kiwi\", 2)\n\n def _scroll_to_tag_and_verify(self, tag_name, group_index):\n \"\"\" Helper method for all scroll to tag tests \"\"\"\n self.notes_page.notes[1].go_to_tag(tag_name)\n\n # Because all the notes (with tags) have the same tags, they will end up ordered alphabetically.\n pear_group = self.notes_page.tag_groups[group_index]\n self.assertEqual(tag_name + \" (3)\", pear_group.title)\n self.assertTrue(pear_group.scrolled_to_top(group_index))\n\n def test_tabs_behaves_correctly(self):\n \"\"\"\n Scenario: Tabs behaves correctly.\n Given I have a course with 5 notes\n When I open Notes page\n Then I see only \"Recent Activity\", \"Location in Course\", and \"Tags\" tabs\n When I run the search with \"note\" query\n And I see that \"Search Results\" tab appears with 4 notes found\n Then I switch to \"Recent Activity\" tab\n And I see all 5 notes\n Then I switch to \"Location in Course\" tab\n And I see all 2 groups and 5 notes\n When I switch back to \"Search Results\" tab\n Then I can still see 4 notes found\n When I close \"Search Results\" tab\n Then I see that \"Recent Activity\" tab becomes active\n And \"Search Results\" tab disappears\n And I see all 5 notes\n \"\"\"\n self._add_default_notes()\n self.notes_page.visit()\n\n # We're on Recent Activity tab.\n self.assertEqual(len(self.notes_page.tabs), 3)\n self.assertEqual([u\"Recent Activity\", u\"Location in Course\", u\"Tags\"], self.notes_page.tabs)\n self.notes_page.search(\"note\")\n # We're on Search Results tab\n self.assertEqual(len(self.notes_page.tabs), 4)\n self.assertIn(u\"Search Results\", self.notes_page.tabs)\n self.assertEqual(len(self.notes_page.notes), 4)\n # We can switch on Recent Activity tab and back.\n self.notes_page.switch_to_tab(\"recent\")\n self.assertEqual(len(self.notes_page.notes), 5)\n self.notes_page.switch_to_tab(\"structure\")\n self.assertEqual(len(self.notes_page.chapter_groups), 2)\n self.assertEqual(len(self.notes_page.notes), 5)\n self.notes_page.switch_to_tab(\"search\")\n self.assertEqual(len(self.notes_page.notes), 4)\n # Can close search results page\n self.notes_page.close_tab()\n self.assertEqual(len(self.notes_page.tabs), 3)\n self.assertNotIn(u\"Search Results\", self.notes_page.tabs)\n self.assertEqual(len(self.notes_page.notes), 5)\n\n def test_open_note_when_accessed_from_notes_page(self):\n \"\"\"\n Scenario: Ensure that the link to the Unit opens a note only once.\n Given I have a course with 2 sequentials that contain respectively one note and two notes\n When I open Notes page\n And I click on the first unit link\n Then I see the note opened on the unit page\n When I switch to the second sequential\n I do not see any note opened\n When I switch back to first sequential\n I do not see any note opened\n \"\"\"\n xblocks = self.course_fixture.get_nested_xblocks(category=\"html\")\n self._add_notes([\n Note(\n usage_id=xblocks[1].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"Third note\",\n quote=\"Annotate this text\",\n updated=datetime(2012, 1, 1, 1, 1, 1, 1).isoformat(),\n ranges=[Range(startOffset=0, endOffset=19)],\n ),\n Note(\n usage_id=xblocks[2].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"Second note\",\n quote=\"Annotate this text\",\n updated=datetime(2013, 1, 1, 1, 1, 1, 1).isoformat(),\n ranges=[Range(startOffset=0, endOffset=19)],\n ),\n Note(\n usage_id=xblocks[0].locator,\n user=self.username,\n course_id=self.course_fixture._course_key,\n text=\"First note\",\n quote=\"Annotate this text\",\n updated=datetime(2014, 1, 1, 1, 1, 1, 1).isoformat(),\n ranges=[Range(startOffset=0, endOffset=19)],\n ),\n ])\n self.notes_page.visit()\n item = self.notes_page.notes[0]\n item.go_to_unit()\n self.courseware_page.wait_for_page()\n note = self.note_unit_page.notes[0]\n self.assertTrue(note.is_visible)\n note = self.note_unit_page.notes[1]\n self.assertFalse(note.is_visible)\n self.course_nav.go_to_sequential_position(2)\n note = self.note_unit_page.notes[0]\n self.assertFalse(note.is_visible)\n self.course_nav.go_to_sequential_position(1)\n note = self.note_unit_page.notes[0]\n self.assertFalse(note.is_visible)\n\n\n@attr('shard_4')\nclass EdxNotesToggleSingleNoteTest(EdxNotesTestMixin):\n \"\"\"\n Tests for toggling single annotation.\n \"\"\"\n\n def setUp(self):\n super(EdxNotesToggleSingleNoteTest, self).setUp()\n self._add_notes()\n self.note_unit_page.visit()\n\n def test_can_toggle_by_clicking_on_highlighted_text(self):\n \"\"\"\n Scenario: User can toggle a single note by clicking on highlighted text.\n Given I have a course with components with notes\n When I click on highlighted text\n And I move mouse out of the note\n Then I see that the note is still shown\n When I click outside the note\n Then I see the the note is closed\n \"\"\"\n note = self.note_unit_page.notes[0]\n\n note.click_on_highlight()\n self.note_unit_page.move_mouse_to(\"body\")\n self.assertTrue(note.is_visible)\n self.note_unit_page.click(\"body\")\n self.assertFalse(note.is_visible)\n\n def test_can_toggle_by_clicking_on_the_note(self):\n \"\"\"\n Scenario: User can toggle a single note by clicking on the note.\n Given I have a course with components with notes\n When I click on the note\n And I move mouse out of the note\n Then I see that the note is still shown\n When I click outside the note\n Then I see the the note is closed\n \"\"\"\n note = self.note_unit_page.notes[0]\n\n note.show().click_on_viewer()\n self.note_unit_page.move_mouse_to(\"body\")\n self.assertTrue(note.is_visible)\n self.note_unit_page.click(\"body\")\n self.assertFalse(note.is_visible)\n\n def test_interaction_between_notes(self):\n \"\"\"\n Scenario: Interactions between notes works well.\n Given I have a course with components with notes\n When I click on highlighted text in the first component\n And I move mouse out of the note\n Then I see that the note is still shown\n When I click on highlighted text in the second component\n Then I see that the new note is shown\n \"\"\"\n note_1 = self.note_unit_page.notes[0]\n note_2 = self.note_unit_page.notes[1]\n\n note_1.click_on_highlight()\n self.note_unit_page.move_mouse_to(\"body\")\n self.assertTrue(note_1.is_visible)\n\n note_2.click_on_highlight()\n self.assertFalse(note_1.is_visible)\n self.assertTrue(note_2.is_visible)\n\n\n@attr('shard_4')\nclass EdxNotesToggleNotesTest(EdxNotesTestMixin):\n \"\"\"\n Tests for toggling visibility of all notes.\n \"\"\"\n\n def setUp(self):\n super(EdxNotesToggleNotesTest, self).setUp()\n self._add_notes()\n self.note_unit_page.visit()\n\n def test_can_disable_all_notes(self):\n \"\"\"\n Scenario: User can disable all notes.\n Given I have a course with components with notes\n And I open the unit with annotatable components\n When I click on \"Show notes\" checkbox\n Then I do not see any notes on the sequential position\n When I change sequential position to \"2\"\n Then I still do not see any notes on the sequential position\n When I go to \"Test Subsection 2\" subsection\n Then I do not see any notes on the subsection\n \"\"\"\n # Disable all notes\n self.note_unit_page.toggle_visibility()\n self.assertEqual(len(self.note_unit_page.notes), 0)\n self.course_nav.go_to_sequential_position(2)\n self.assertEqual(len(self.note_unit_page.notes), 0)\n self.course_nav.go_to_section(u\"Test Section 1\", u\"Test Subsection 2\")\n self.assertEqual(len(self.note_unit_page.notes), 0)\n\n def test_can_reenable_all_notes(self):\n \"\"\"\n Scenario: User can toggle notes visibility.\n Given I have a course with components with notes\n And I open the unit with annotatable components\n When I click on \"Show notes\" checkbox\n Then I do not see any notes on the sequential position\n When I click on \"Show notes\" checkbox again\n Then I see that all notes appear\n When I change sequential position to \"2\"\n Then I still can see all notes on the sequential position\n When I go to \"Test Subsection 2\" subsection\n Then I can see all notes on the subsection\n \"\"\"\n # Disable notes\n self.note_unit_page.toggle_visibility()\n self.assertEqual(len(self.note_unit_page.notes), 0)\n # Enable notes to make sure that I can enable notes without refreshing\n # the page.\n self.note_unit_page.toggle_visibility()\n self.assertGreater(len(self.note_unit_page.notes), 0)\n self.course_nav.go_to_sequential_position(2)\n self.assertGreater(len(self.note_unit_page.notes), 0)\n self.course_nav.go_to_section(u\"Test Section 1\", u\"Test Subsection 2\")\n self.assertGreater(len(self.note_unit_page.notes), 0)\n"},"license":{"kind":"string","value":"agpl-3.0"}}},{"rowIdx":476126,"cells":{"repo_name":{"kind":"string","value":"LouisPlisso/pytomo"},"path":{"kind":"string","value":"pytomo/fpdf/fonts.py"},"copies":{"kind":"string","value":"34"},"size":{"kind":"string","value":"26574"},"content":{"kind":"string","value":"#!/usr/bin/env python\r\n# -*- coding: latin-1 -*-\r\n\r\n# Fonts:\r\n\r\nfpdf_charwidths = {}\r\n\r\nfpdf_charwidths['courier']={}\r\n\r\nfor i in xrange(0,256):\r\n fpdf_charwidths['courier'][chr(i)]=600\r\n fpdf_charwidths['courierB']=fpdf_charwidths['courier']\r\n fpdf_charwidths['courierI']=fpdf_charwidths['courier']\r\n fpdf_charwidths['courierBI']=fpdf_charwidths['courier']\r\n\r\nfpdf_charwidths['helvetica']={\r\n '\\x00':278,'\\x01':278,'\\x02':278,'\\x03':278,'\\x04':278,'\\x05':278,'\\x06':278,'\\x07':278,'\\x08':278,'\\t':278,'\\n':278,'\\x0b':278,'\\x0c':278,'\\r':278,'\\x0e':278,'\\x0f':278,'\\x10':278,'\\x11':278,'\\x12':278,'\\x13':278,'\\x14':278,'\\x15':278,\r\n '\\x16':278,'\\x17':278,'\\x18':278,'\\x19':278,'\\x1a':278,'\\x1b':278,'\\x1c':278,'\\x1d':278,'\\x1e':278,'\\x1f':278,' ':278,'!':278,'\"':355,'#':556,'$':556,'%':889,'&':667,'\\'':191,'(':333,')':333,'*':389,'+':584,\r\n ',':278,'-':333,'.':278,'/':278,'0':556,'1':556,'2':556,'3':556,'4':556,'5':556,'6':556,'7':556,'8':556,'9':556,':':278,';':278,'<':584,'=':584,'>':584,'?':556,'@':1015,'A':667,\r\n 'B':667,'C':722,'D':722,'E':667,'F':611,'G':778,'H':722,'I':278,'J':500,'K':667,'L':556,'M':833,'N':722,'O':778,'P':667,'Q':778,'R':722,'S':667,'T':611,'U':722,'V':667,'W':944,\r\n 'X':667,'Y':667,'Z':611,'[':278,'\\\\':278,']':278,'^':469,'_':556,'`':333,'a':556,'b':556,'c':500,'d':556,'e':556,'f':278,'g':556,'h':556,'i':222,'j':222,'k':500,'l':222,'m':833,\r\n 'n':556,'o':556,'p':556,'q':556,'r':333,'s':500,'t':278,'u':556,'v':500,'w':722,'x':500,'y':500,'z':500,'{':334,'|':260,'}':334,'~':584,'\\x7f':350,'\\x80':556,'\\x81':350,'\\x82':222,'\\x83':556,\r\n '\\x84':333,'\\x85':1000,'\\x86':556,'\\x87':556,'\\x88':333,'\\x89':1000,'\\x8a':667,'\\x8b':333,'\\x8c':1000,'\\x8d':350,'\\x8e':611,'\\x8f':350,'\\x90':350,'\\x91':222,'\\x92':222,'\\x93':333,'\\x94':333,'\\x95':350,'\\x96':556,'\\x97':1000,'\\x98':333,'\\x99':1000,\r\n '\\x9a':500,'\\x9b':333,'\\x9c':944,'\\x9d':350,'\\x9e':500,'\\x9f':667,'\\xa0':278,'\\xa1':333,'\\xa2':556,'\\xa3':556,'\\xa4':556,'\\xa5':556,'\\xa6':260,'\\xa7':556,'\\xa8':333,'\\xa9':737,'\\xaa':370,'\\xab':556,'\\xac':584,'\\xad':333,'\\xae':737,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':584,'\\xb2':333,'\\xb3':333,'\\xb4':333,'\\xb5':556,'\\xb6':537,'\\xb7':278,'\\xb8':333,'\\xb9':333,'\\xba':365,'\\xbb':556,'\\xbc':834,'\\xbd':834,'\\xbe':834,'\\xbf':611,'\\xc0':667,'\\xc1':667,'\\xc2':667,'\\xc3':667,'\\xc4':667,'\\xc5':667,\r\n '\\xc6':1000,'\\xc7':722,'\\xc8':667,'\\xc9':667,'\\xca':667,'\\xcb':667,'\\xcc':278,'\\xcd':278,'\\xce':278,'\\xcf':278,'\\xd0':722,'\\xd1':722,'\\xd2':778,'\\xd3':778,'\\xd4':778,'\\xd5':778,'\\xd6':778,'\\xd7':584,'\\xd8':778,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':667,'\\xde':667,'\\xdf':611,'\\xe0':556,'\\xe1':556,'\\xe2':556,'\\xe3':556,'\\xe4':556,'\\xe5':556,'\\xe6':889,'\\xe7':500,'\\xe8':556,'\\xe9':556,'\\xea':556,'\\xeb':556,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':556,'\\xf1':556,\r\n '\\xf2':556,'\\xf3':556,'\\xf4':556,'\\xf5':556,'\\xf6':556,'\\xf7':584,'\\xf8':611,'\\xf9':556,'\\xfa':556,'\\xfb':556,'\\xfc':556,'\\xfd':500,'\\xfe':556,'\\xff':500}\r\n\r\nfpdf_charwidths['helveticaB']={\r\n '\\x00':278,'\\x01':278,'\\x02':278,'\\x03':278,'\\x04':278,'\\x05':278,'\\x06':278,'\\x07':278,'\\x08':278,'\\t':278,'\\n':278,'\\x0b':278,'\\x0c':278,'\\r':278,'\\x0e':278,'\\x0f':278,'\\x10':278,'\\x11':278,'\\x12':278,'\\x13':278,'\\x14':278,'\\x15':278,\r\n '\\x16':278,'\\x17':278,'\\x18':278,'\\x19':278,'\\x1a':278,'\\x1b':278,'\\x1c':278,'\\x1d':278,'\\x1e':278,'\\x1f':278,' ':278,'!':333,'\"':474,'#':556,'$':556,'%':889,'&':722,'\\'':238,'(':333,')':333,'*':389,'+':584,\r\n ',':278,'-':333,'.':278,'/':278,'0':556,'1':556,'2':556,'3':556,'4':556,'5':556,'6':556,'7':556,'8':556,'9':556,':':333,';':333,'<':584,'=':584,'>':584,'?':611,'@':975,'A':722,\r\n 'B':722,'C':722,'D':722,'E':667,'F':611,'G':778,'H':722,'I':278,'J':556,'K':722,'L':611,'M':833,'N':722,'O':778,'P':667,'Q':778,'R':722,'S':667,'T':611,'U':722,'V':667,'W':944,\r\n 'X':667,'Y':667,'Z':611,'[':333,'\\\\':278,']':333,'^':584,'_':556,'`':333,'a':556,'b':611,'c':556,'d':611,'e':556,'f':333,'g':611,'h':611,'i':278,'j':278,'k':556,'l':278,'m':889,\r\n 'n':611,'o':611,'p':611,'q':611,'r':389,'s':556,'t':333,'u':611,'v':556,'w':778,'x':556,'y':556,'z':500,'{':389,'|':280,'}':389,'~':584,'\\x7f':350,'\\x80':556,'\\x81':350,'\\x82':278,'\\x83':556,\r\n '\\x84':500,'\\x85':1000,'\\x86':556,'\\x87':556,'\\x88':333,'\\x89':1000,'\\x8a':667,'\\x8b':333,'\\x8c':1000,'\\x8d':350,'\\x8e':611,'\\x8f':350,'\\x90':350,'\\x91':278,'\\x92':278,'\\x93':500,'\\x94':500,'\\x95':350,'\\x96':556,'\\x97':1000,'\\x98':333,'\\x99':1000,\r\n '\\x9a':556,'\\x9b':333,'\\x9c':944,'\\x9d':350,'\\x9e':500,'\\x9f':667,'\\xa0':278,'\\xa1':333,'\\xa2':556,'\\xa3':556,'\\xa4':556,'\\xa5':556,'\\xa6':280,'\\xa7':556,'\\xa8':333,'\\xa9':737,'\\xaa':370,'\\xab':556,'\\xac':584,'\\xad':333,'\\xae':737,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':584,'\\xb2':333,'\\xb3':333,'\\xb4':333,'\\xb5':611,'\\xb6':556,'\\xb7':278,'\\xb8':333,'\\xb9':333,'\\xba':365,'\\xbb':556,'\\xbc':834,'\\xbd':834,'\\xbe':834,'\\xbf':611,'\\xc0':722,'\\xc1':722,'\\xc2':722,'\\xc3':722,'\\xc4':722,'\\xc5':722,\r\n '\\xc6':1000,'\\xc7':722,'\\xc8':667,'\\xc9':667,'\\xca':667,'\\xcb':667,'\\xcc':278,'\\xcd':278,'\\xce':278,'\\xcf':278,'\\xd0':722,'\\xd1':722,'\\xd2':778,'\\xd3':778,'\\xd4':778,'\\xd5':778,'\\xd6':778,'\\xd7':584,'\\xd8':778,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':667,'\\xde':667,'\\xdf':611,'\\xe0':556,'\\xe1':556,'\\xe2':556,'\\xe3':556,'\\xe4':556,'\\xe5':556,'\\xe6':889,'\\xe7':556,'\\xe8':556,'\\xe9':556,'\\xea':556,'\\xeb':556,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':611,'\\xf1':611,\r\n '\\xf2':611,'\\xf3':611,'\\xf4':611,'\\xf5':611,'\\xf6':611,'\\xf7':584,'\\xf8':611,'\\xf9':611,'\\xfa':611,'\\xfb':611,'\\xfc':611,'\\xfd':556,'\\xfe':611,'\\xff':556\r\n}\r\n\r\nfpdf_charwidths['helveticaBI']={\r\n '\\x00':278,'\\x01':278,'\\x02':278,'\\x03':278,'\\x04':278,'\\x05':278,'\\x06':278,'\\x07':278,'\\x08':278,'\\t':278,'\\n':278,'\\x0b':278,'\\x0c':278,'\\r':278,'\\x0e':278,'\\x0f':278,'\\x10':278,'\\x11':278,'\\x12':278,'\\x13':278,'\\x14':278,'\\x15':278,\r\n '\\x16':278,'\\x17':278,'\\x18':278,'\\x19':278,'\\x1a':278,'\\x1b':278,'\\x1c':278,'\\x1d':278,'\\x1e':278,'\\x1f':278,' ':278,'!':333,'\"':474,'#':556,'$':556,'%':889,'&':722,'\\'':238,'(':333,')':333,'*':389,'+':584,\r\n ',':278,'-':333,'.':278,'/':278,'0':556,'1':556,'2':556,'3':556,'4':556,'5':556,'6':556,'7':556,'8':556,'9':556,':':333,';':333,'<':584,'=':584,'>':584,'?':611,'@':975,'A':722,\r\n 'B':722,'C':722,'D':722,'E':667,'F':611,'G':778,'H':722,'I':278,'J':556,'K':722,'L':611,'M':833,'N':722,'O':778,'P':667,'Q':778,'R':722,'S':667,'T':611,'U':722,'V':667,'W':944,\r\n 'X':667,'Y':667,'Z':611,'[':333,'\\\\':278,']':333,'^':584,'_':556,'`':333,'a':556,'b':611,'c':556,'d':611,'e':556,'f':333,'g':611,'h':611,'i':278,'j':278,'k':556,'l':278,'m':889,\r\n 'n':611,'o':611,'p':611,'q':611,'r':389,'s':556,'t':333,'u':611,'v':556,'w':778,'x':556,'y':556,'z':500,'{':389,'|':280,'}':389,'~':584,'\\x7f':350,'\\x80':556,'\\x81':350,'\\x82':278,'\\x83':556,\r\n '\\x84':500,'\\x85':1000,'\\x86':556,'\\x87':556,'\\x88':333,'\\x89':1000,'\\x8a':667,'\\x8b':333,'\\x8c':1000,'\\x8d':350,'\\x8e':611,'\\x8f':350,'\\x90':350,'\\x91':278,'\\x92':278,'\\x93':500,'\\x94':500,'\\x95':350,'\\x96':556,'\\x97':1000,'\\x98':333,'\\x99':1000,\r\n '\\x9a':556,'\\x9b':333,'\\x9c':944,'\\x9d':350,'\\x9e':500,'\\x9f':667,'\\xa0':278,'\\xa1':333,'\\xa2':556,'\\xa3':556,'\\xa4':556,'\\xa5':556,'\\xa6':280,'\\xa7':556,'\\xa8':333,'\\xa9':737,'\\xaa':370,'\\xab':556,'\\xac':584,'\\xad':333,'\\xae':737,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':584,'\\xb2':333,'\\xb3':333,'\\xb4':333,'\\xb5':611,'\\xb6':556,'\\xb7':278,'\\xb8':333,'\\xb9':333,'\\xba':365,'\\xbb':556,'\\xbc':834,'\\xbd':834,'\\xbe':834,'\\xbf':611,'\\xc0':722,'\\xc1':722,'\\xc2':722,'\\xc3':722,'\\xc4':722,'\\xc5':722,\r\n '\\xc6':1000,'\\xc7':722,'\\xc8':667,'\\xc9':667,'\\xca':667,'\\xcb':667,'\\xcc':278,'\\xcd':278,'\\xce':278,'\\xcf':278,'\\xd0':722,'\\xd1':722,'\\xd2':778,'\\xd3':778,'\\xd4':778,'\\xd5':778,'\\xd6':778,'\\xd7':584,'\\xd8':778,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':667,'\\xde':667,'\\xdf':611,'\\xe0':556,'\\xe1':556,'\\xe2':556,'\\xe3':556,'\\xe4':556,'\\xe5':556,'\\xe6':889,'\\xe7':556,'\\xe8':556,'\\xe9':556,'\\xea':556,'\\xeb':556,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':611,'\\xf1':611,\r\n '\\xf2':611,'\\xf3':611,'\\xf4':611,'\\xf5':611,'\\xf6':611,'\\xf7':584,'\\xf8':611,'\\xf9':611,'\\xfa':611,'\\xfb':611,'\\xfc':611,'\\xfd':556,'\\xfe':611,'\\xff':556}\r\n\r\nfpdf_charwidths['helveticaI']={\r\n '\\x00':278,'\\x01':278,'\\x02':278,'\\x03':278,'\\x04':278,'\\x05':278,'\\x06':278,'\\x07':278,'\\x08':278,'\\t':278,'\\n':278,'\\x0b':278,'\\x0c':278,'\\r':278,'\\x0e':278,'\\x0f':278,'\\x10':278,'\\x11':278,'\\x12':278,'\\x13':278,'\\x14':278,'\\x15':278,\r\n '\\x16':278,'\\x17':278,'\\x18':278,'\\x19':278,'\\x1a':278,'\\x1b':278,'\\x1c':278,'\\x1d':278,'\\x1e':278,'\\x1f':278,' ':278,'!':278,'\"':355,'#':556,'$':556,'%':889,'&':667,'\\'':191,'(':333,')':333,'*':389,'+':584,\r\n ',':278,'-':333,'.':278,'/':278,'0':556,'1':556,'2':556,'3':556,'4':556,'5':556,'6':556,'7':556,'8':556,'9':556,':':278,';':278,'<':584,'=':584,'>':584,'?':556,'@':1015,'A':667,\r\n 'B':667,'C':722,'D':722,'E':667,'F':611,'G':778,'H':722,'I':278,'J':500,'K':667,'L':556,'M':833,'N':722,'O':778,'P':667,'Q':778,'R':722,'S':667,'T':611,'U':722,'V':667,'W':944,\r\n 'X':667,'Y':667,'Z':611,'[':278,'\\\\':278,']':278,'^':469,'_':556,'`':333,'a':556,'b':556,'c':500,'d':556,'e':556,'f':278,'g':556,'h':556,'i':222,'j':222,'k':500,'l':222,'m':833,\r\n 'n':556,'o':556,'p':556,'q':556,'r':333,'s':500,'t':278,'u':556,'v':500,'w':722,'x':500,'y':500,'z':500,'{':334,'|':260,'}':334,'~':584,'\\x7f':350,'\\x80':556,'\\x81':350,'\\x82':222,'\\x83':556,\r\n '\\x84':333,'\\x85':1000,'\\x86':556,'\\x87':556,'\\x88':333,'\\x89':1000,'\\x8a':667,'\\x8b':333,'\\x8c':1000,'\\x8d':350,'\\x8e':611,'\\x8f':350,'\\x90':350,'\\x91':222,'\\x92':222,'\\x93':333,'\\x94':333,'\\x95':350,'\\x96':556,'\\x97':1000,'\\x98':333,'\\x99':1000,\r\n '\\x9a':500,'\\x9b':333,'\\x9c':944,'\\x9d':350,'\\x9e':500,'\\x9f':667,'\\xa0':278,'\\xa1':333,'\\xa2':556,'\\xa3':556,'\\xa4':556,'\\xa5':556,'\\xa6':260,'\\xa7':556,'\\xa8':333,'\\xa9':737,'\\xaa':370,'\\xab':556,'\\xac':584,'\\xad':333,'\\xae':737,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':584,'\\xb2':333,'\\xb3':333,'\\xb4':333,'\\xb5':556,'\\xb6':537,'\\xb7':278,'\\xb8':333,'\\xb9':333,'\\xba':365,'\\xbb':556,'\\xbc':834,'\\xbd':834,'\\xbe':834,'\\xbf':611,'\\xc0':667,'\\xc1':667,'\\xc2':667,'\\xc3':667,'\\xc4':667,'\\xc5':667,\r\n '\\xc6':1000,'\\xc7':722,'\\xc8':667,'\\xc9':667,'\\xca':667,'\\xcb':667,'\\xcc':278,'\\xcd':278,'\\xce':278,'\\xcf':278,'\\xd0':722,'\\xd1':722,'\\xd2':778,'\\xd3':778,'\\xd4':778,'\\xd5':778,'\\xd6':778,'\\xd7':584,'\\xd8':778,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':667,'\\xde':667,'\\xdf':611,'\\xe0':556,'\\xe1':556,'\\xe2':556,'\\xe3':556,'\\xe4':556,'\\xe5':556,'\\xe6':889,'\\xe7':500,'\\xe8':556,'\\xe9':556,'\\xea':556,'\\xeb':556,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':556,'\\xf1':556,\r\n '\\xf2':556,'\\xf3':556,'\\xf4':556,'\\xf5':556,'\\xf6':556,'\\xf7':584,'\\xf8':611,'\\xf9':556,'\\xfa':556,'\\xfb':556,'\\xfc':556,'\\xfd':500,'\\xfe':556,'\\xff':500}\r\n\r\nfpdf_charwidths['symbol']={\r\n '\\x00':250,'\\x01':250,'\\x02':250,'\\x03':250,'\\x04':250,'\\x05':250,'\\x06':250,'\\x07':250,'\\x08':250,'\\t':250,'\\n':250,'\\x0b':250,'\\x0c':250,'\\r':250,'\\x0e':250,'\\x0f':250,'\\x10':250,'\\x11':250,'\\x12':250,'\\x13':250,'\\x14':250,'\\x15':250,\r\n '\\x16':250,'\\x17':250,'\\x18':250,'\\x19':250,'\\x1a':250,'\\x1b':250,'\\x1c':250,'\\x1d':250,'\\x1e':250,'\\x1f':250,' ':250,'!':333,'\"':713,'#':500,'$':549,'%':833,'&':778,'\\'':439,'(':333,')':333,'*':500,'+':549,\r\n ',':250,'-':549,'.':250,'/':278,'0':500,'1':500,'2':500,'3':500,'4':500,'5':500,'6':500,'7':500,'8':500,'9':500,':':278,';':278,'<':549,'=':549,'>':549,'?':444,'@':549,'A':722,\r\n 'B':667,'C':722,'D':612,'E':611,'F':763,'G':603,'H':722,'I':333,'J':631,'K':722,'L':686,'M':889,'N':722,'O':722,'P':768,'Q':741,'R':556,'S':592,'T':611,'U':690,'V':439,'W':768,\r\n 'X':645,'Y':795,'Z':611,'[':333,'\\\\':863,']':333,'^':658,'_':500,'`':500,'a':631,'b':549,'c':549,'d':494,'e':439,'f':521,'g':411,'h':603,'i':329,'j':603,'k':549,'l':549,'m':576,\r\n 'n':521,'o':549,'p':549,'q':521,'r':549,'s':603,'t':439,'u':576,'v':713,'w':686,'x':493,'y':686,'z':494,'{':480,'|':200,'}':480,'~':549,'\\x7f':0,'\\x80':0,'\\x81':0,'\\x82':0,'\\x83':0,\r\n '\\x84':0,'\\x85':0,'\\x86':0,'\\x87':0,'\\x88':0,'\\x89':0,'\\x8a':0,'\\x8b':0,'\\x8c':0,'\\x8d':0,'\\x8e':0,'\\x8f':0,'\\x90':0,'\\x91':0,'\\x92':0,'\\x93':0,'\\x94':0,'\\x95':0,'\\x96':0,'\\x97':0,'\\x98':0,'\\x99':0,\r\n '\\x9a':0,'\\x9b':0,'\\x9c':0,'\\x9d':0,'\\x9e':0,'\\x9f':0,'\\xa0':750,'\\xa1':620,'\\xa2':247,'\\xa3':549,'\\xa4':167,'\\xa5':713,'\\xa6':500,'\\xa7':753,'\\xa8':753,'\\xa9':753,'\\xaa':753,'\\xab':1042,'\\xac':987,'\\xad':603,'\\xae':987,'\\xaf':603,\r\n '\\xb0':400,'\\xb1':549,'\\xb2':411,'\\xb3':549,'\\xb4':549,'\\xb5':713,'\\xb6':494,'\\xb7':460,'\\xb8':549,'\\xb9':549,'\\xba':549,'\\xbb':549,'\\xbc':1000,'\\xbd':603,'\\xbe':1000,'\\xbf':658,'\\xc0':823,'\\xc1':686,'\\xc2':795,'\\xc3':987,'\\xc4':768,'\\xc5':768,\r\n '\\xc6':823,'\\xc7':768,'\\xc8':768,'\\xc9':713,'\\xca':713,'\\xcb':713,'\\xcc':713,'\\xcd':713,'\\xce':713,'\\xcf':713,'\\xd0':768,'\\xd1':713,'\\xd2':790,'\\xd3':790,'\\xd4':890,'\\xd5':823,'\\xd6':549,'\\xd7':250,'\\xd8':713,'\\xd9':603,'\\xda':603,'\\xdb':1042,\r\n '\\xdc':987,'\\xdd':603,'\\xde':987,'\\xdf':603,'\\xe0':494,'\\xe1':329,'\\xe2':790,'\\xe3':790,'\\xe4':786,'\\xe5':713,'\\xe6':384,'\\xe7':384,'\\xe8':384,'\\xe9':384,'\\xea':384,'\\xeb':384,'\\xec':494,'\\xed':494,'\\xee':494,'\\xef':494,'\\xf0':0,'\\xf1':329,\r\n '\\xf2':274,'\\xf3':686,'\\xf4':686,'\\xf5':686,'\\xf6':384,'\\xf7':384,'\\xf8':384,'\\xf9':384,'\\xfa':384,'\\xfb':384,'\\xfc':494,'\\xfd':494,'\\xfe':494,'\\xff':0}\r\n \r\nfpdf_charwidths['times']={\r\n '\\x00':250,'\\x01':250,'\\x02':250,'\\x03':250,'\\x04':250,'\\x05':250,'\\x06':250,'\\x07':250,'\\x08':250,'\\t':250,'\\n':250,'\\x0b':250,'\\x0c':250,'\\r':250,'\\x0e':250,'\\x0f':250,'\\x10':250,'\\x11':250,'\\x12':250,'\\x13':250,'\\x14':250,'\\x15':250,\r\n '\\x16':250,'\\x17':250,'\\x18':250,'\\x19':250,'\\x1a':250,'\\x1b':250,'\\x1c':250,'\\x1d':250,'\\x1e':250,'\\x1f':250,' ':250,'!':333,'\"':408,'#':500,'$':500,'%':833,'&':778,'\\'':180,'(':333,')':333,'*':500,'+':564,\r\n ',':250,'-':333,'.':250,'/':278,'0':500,'1':500,'2':500,'3':500,'4':500,'5':500,'6':500,'7':500,'8':500,'9':500,':':278,';':278,'<':564,'=':564,'>':564,'?':444,'@':921,'A':722,\r\n 'B':667,'C':667,'D':722,'E':611,'F':556,'G':722,'H':722,'I':333,'J':389,'K':722,'L':611,'M':889,'N':722,'O':722,'P':556,'Q':722,'R':667,'S':556,'T':611,'U':722,'V':722,'W':944,\r\n 'X':722,'Y':722,'Z':611,'[':333,'\\\\':278,']':333,'^':469,'_':500,'`':333,'a':444,'b':500,'c':444,'d':500,'e':444,'f':333,'g':500,'h':500,'i':278,'j':278,'k':500,'l':278,'m':778,\r\n 'n':500,'o':500,'p':500,'q':500,'r':333,'s':389,'t':278,'u':500,'v':500,'w':722,'x':500,'y':500,'z':444,'{':480,'|':200,'}':480,'~':541,'\\x7f':350,'\\x80':500,'\\x81':350,'\\x82':333,'\\x83':500,\r\n '\\x84':444,'\\x85':1000,'\\x86':500,'\\x87':500,'\\x88':333,'\\x89':1000,'\\x8a':556,'\\x8b':333,'\\x8c':889,'\\x8d':350,'\\x8e':611,'\\x8f':350,'\\x90':350,'\\x91':333,'\\x92':333,'\\x93':444,'\\x94':444,'\\x95':350,'\\x96':500,'\\x97':1000,'\\x98':333,'\\x99':980,\r\n '\\x9a':389,'\\x9b':333,'\\x9c':722,'\\x9d':350,'\\x9e':444,'\\x9f':722,'\\xa0':250,'\\xa1':333,'\\xa2':500,'\\xa3':500,'\\xa4':500,'\\xa5':500,'\\xa6':200,'\\xa7':500,'\\xa8':333,'\\xa9':760,'\\xaa':276,'\\xab':500,'\\xac':564,'\\xad':333,'\\xae':760,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':564,'\\xb2':300,'\\xb3':300,'\\xb4':333,'\\xb5':500,'\\xb6':453,'\\xb7':250,'\\xb8':333,'\\xb9':300,'\\xba':310,'\\xbb':500,'\\xbc':750,'\\xbd':750,'\\xbe':750,'\\xbf':444,'\\xc0':722,'\\xc1':722,'\\xc2':722,'\\xc3':722,'\\xc4':722,'\\xc5':722,\r\n '\\xc6':889,'\\xc7':667,'\\xc8':611,'\\xc9':611,'\\xca':611,'\\xcb':611,'\\xcc':333,'\\xcd':333,'\\xce':333,'\\xcf':333,'\\xd0':722,'\\xd1':722,'\\xd2':722,'\\xd3':722,'\\xd4':722,'\\xd5':722,'\\xd6':722,'\\xd7':564,'\\xd8':722,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':722,'\\xde':556,'\\xdf':500,'\\xe0':444,'\\xe1':444,'\\xe2':444,'\\xe3':444,'\\xe4':444,'\\xe5':444,'\\xe6':667,'\\xe7':444,'\\xe8':444,'\\xe9':444,'\\xea':444,'\\xeb':444,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':500,'\\xf1':500,\r\n '\\xf2':500,'\\xf3':500,'\\xf4':500,'\\xf5':500,'\\xf6':500,'\\xf7':564,'\\xf8':500,'\\xf9':500,'\\xfa':500,'\\xfb':500,'\\xfc':500,'\\xfd':500,'\\xfe':500,'\\xff':500}\r\n\r\nfpdf_charwidths['timesB']={\r\n '\\x00':250,'\\x01':250,'\\x02':250,'\\x03':250,'\\x04':250,'\\x05':250,'\\x06':250,'\\x07':250,'\\x08':250,'\\t':250,'\\n':250,'\\x0b':250,'\\x0c':250,'\\r':250,'\\x0e':250,'\\x0f':250,'\\x10':250,'\\x11':250,'\\x12':250,'\\x13':250,'\\x14':250,'\\x15':250,\r\n '\\x16':250,'\\x17':250,'\\x18':250,'\\x19':250,'\\x1a':250,'\\x1b':250,'\\x1c':250,'\\x1d':250,'\\x1e':250,'\\x1f':250,' ':250,'!':333,'\"':555,'#':500,'$':500,'%':1000,'&':833,'\\'':278,'(':333,')':333,'*':500,'+':570,\r\n ',':250,'-':333,'.':250,'/':278,'0':500,'1':500,'2':500,'3':500,'4':500,'5':500,'6':500,'7':500,'8':500,'9':500,':':333,';':333,'<':570,'=':570,'>':570,'?':500,'@':930,'A':722,\r\n 'B':667,'C':722,'D':722,'E':667,'F':611,'G':778,'H':778,'I':389,'J':500,'K':778,'L':667,'M':944,'N':722,'O':778,'P':611,'Q':778,'R':722,'S':556,'T':667,'U':722,'V':722,'W':1000,\r\n 'X':722,'Y':722,'Z':667,'[':333,'\\\\':278,']':333,'^':581,'_':500,'`':333,'a':500,'b':556,'c':444,'d':556,'e':444,'f':333,'g':500,'h':556,'i':278,'j':333,'k':556,'l':278,'m':833,\r\n 'n':556,'o':500,'p':556,'q':556,'r':444,'s':389,'t':333,'u':556,'v':500,'w':722,'x':500,'y':500,'z':444,'{':394,'|':220,'}':394,'~':520,'\\x7f':350,'\\x80':500,'\\x81':350,'\\x82':333,'\\x83':500,\r\n '\\x84':500,'\\x85':1000,'\\x86':500,'\\x87':500,'\\x88':333,'\\x89':1000,'\\x8a':556,'\\x8b':333,'\\x8c':1000,'\\x8d':350,'\\x8e':667,'\\x8f':350,'\\x90':350,'\\x91':333,'\\x92':333,'\\x93':500,'\\x94':500,'\\x95':350,'\\x96':500,'\\x97':1000,'\\x98':333,'\\x99':1000,\r\n '\\x9a':389,'\\x9b':333,'\\x9c':722,'\\x9d':350,'\\x9e':444,'\\x9f':722,'\\xa0':250,'\\xa1':333,'\\xa2':500,'\\xa3':500,'\\xa4':500,'\\xa5':500,'\\xa6':220,'\\xa7':500,'\\xa8':333,'\\xa9':747,'\\xaa':300,'\\xab':500,'\\xac':570,'\\xad':333,'\\xae':747,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':570,'\\xb2':300,'\\xb3':300,'\\xb4':333,'\\xb5':556,'\\xb6':540,'\\xb7':250,'\\xb8':333,'\\xb9':300,'\\xba':330,'\\xbb':500,'\\xbc':750,'\\xbd':750,'\\xbe':750,'\\xbf':500,'\\xc0':722,'\\xc1':722,'\\xc2':722,'\\xc3':722,'\\xc4':722,'\\xc5':722,\r\n '\\xc6':1000,'\\xc7':722,'\\xc8':667,'\\xc9':667,'\\xca':667,'\\xcb':667,'\\xcc':389,'\\xcd':389,'\\xce':389,'\\xcf':389,'\\xd0':722,'\\xd1':722,'\\xd2':778,'\\xd3':778,'\\xd4':778,'\\xd5':778,'\\xd6':778,'\\xd7':570,'\\xd8':778,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':722,'\\xde':611,'\\xdf':556,'\\xe0':500,'\\xe1':500,'\\xe2':500,'\\xe3':500,'\\xe4':500,'\\xe5':500,'\\xe6':722,'\\xe7':444,'\\xe8':444,'\\xe9':444,'\\xea':444,'\\xeb':444,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':500,'\\xf1':556,\r\n '\\xf2':500,'\\xf3':500,'\\xf4':500,'\\xf5':500,'\\xf6':500,'\\xf7':570,'\\xf8':500,'\\xf9':556,'\\xfa':556,'\\xfb':556,'\\xfc':556,'\\xfd':500,'\\xfe':556,'\\xff':500}\r\n \r\nfpdf_charwidths['timesBI']={\r\n '\\x00':250,'\\x01':250,'\\x02':250,'\\x03':250,'\\x04':250,'\\x05':250,'\\x06':250,'\\x07':250,'\\x08':250,'\\t':250,'\\n':250,'\\x0b':250,'\\x0c':250,'\\r':250,'\\x0e':250,'\\x0f':250,'\\x10':250,'\\x11':250,'\\x12':250,'\\x13':250,'\\x14':250,'\\x15':250,\r\n '\\x16':250,'\\x17':250,'\\x18':250,'\\x19':250,'\\x1a':250,'\\x1b':250,'\\x1c':250,'\\x1d':250,'\\x1e':250,'\\x1f':250,' ':250,'!':389,'\"':555,'#':500,'$':500,'%':833,'&':778,'\\'':278,'(':333,')':333,'*':500,'+':570,\r\n ',':250,'-':333,'.':250,'/':278,'0':500,'1':500,'2':500,'3':500,'4':500,'5':500,'6':500,'7':500,'8':500,'9':500,':':333,';':333,'<':570,'=':570,'>':570,'?':500,'@':832,'A':667,\r\n 'B':667,'C':667,'D':722,'E':667,'F':667,'G':722,'H':778,'I':389,'J':500,'K':667,'L':611,'M':889,'N':722,'O':722,'P':611,'Q':722,'R':667,'S':556,'T':611,'U':722,'V':667,'W':889,\r\n 'X':667,'Y':611,'Z':611,'[':333,'\\\\':278,']':333,'^':570,'_':500,'`':333,'a':500,'b':500,'c':444,'d':500,'e':444,'f':333,'g':500,'h':556,'i':278,'j':278,'k':500,'l':278,'m':778,\r\n 'n':556,'o':500,'p':500,'q':500,'r':389,'s':389,'t':278,'u':556,'v':444,'w':667,'x':500,'y':444,'z':389,'{':348,'|':220,'}':348,'~':570,'\\x7f':350,'\\x80':500,'\\x81':350,'\\x82':333,'\\x83':500,\r\n '\\x84':500,'\\x85':1000,'\\x86':500,'\\x87':500,'\\x88':333,'\\x89':1000,'\\x8a':556,'\\x8b':333,'\\x8c':944,'\\x8d':350,'\\x8e':611,'\\x8f':350,'\\x90':350,'\\x91':333,'\\x92':333,'\\x93':500,'\\x94':500,'\\x95':350,'\\x96':500,'\\x97':1000,'\\x98':333,'\\x99':1000,\r\n '\\x9a':389,'\\x9b':333,'\\x9c':722,'\\x9d':350,'\\x9e':389,'\\x9f':611,'\\xa0':250,'\\xa1':389,'\\xa2':500,'\\xa3':500,'\\xa4':500,'\\xa5':500,'\\xa6':220,'\\xa7':500,'\\xa8':333,'\\xa9':747,'\\xaa':266,'\\xab':500,'\\xac':606,'\\xad':333,'\\xae':747,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':570,'\\xb2':300,'\\xb3':300,'\\xb4':333,'\\xb5':576,'\\xb6':500,'\\xb7':250,'\\xb8':333,'\\xb9':300,'\\xba':300,'\\xbb':500,'\\xbc':750,'\\xbd':750,'\\xbe':750,'\\xbf':500,'\\xc0':667,'\\xc1':667,'\\xc2':667,'\\xc3':667,'\\xc4':667,'\\xc5':667,\r\n '\\xc6':944,'\\xc7':667,'\\xc8':667,'\\xc9':667,'\\xca':667,'\\xcb':667,'\\xcc':389,'\\xcd':389,'\\xce':389,'\\xcf':389,'\\xd0':722,'\\xd1':722,'\\xd2':722,'\\xd3':722,'\\xd4':722,'\\xd5':722,'\\xd6':722,'\\xd7':570,'\\xd8':722,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':611,'\\xde':611,'\\xdf':500,'\\xe0':500,'\\xe1':500,'\\xe2':500,'\\xe3':500,'\\xe4':500,'\\xe5':500,'\\xe6':722,'\\xe7':444,'\\xe8':444,'\\xe9':444,'\\xea':444,'\\xeb':444,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':500,'\\xf1':556,\r\n '\\xf2':500,'\\xf3':500,'\\xf4':500,'\\xf5':500,'\\xf6':500,'\\xf7':570,'\\xf8':500,'\\xf9':556,'\\xfa':556,'\\xfb':556,'\\xfc':556,'\\xfd':444,'\\xfe':500,'\\xff':444}\r\n\r\nfpdf_charwidths['timesI']={\r\n '\\x00':250,'\\x01':250,'\\x02':250,'\\x03':250,'\\x04':250,'\\x05':250,'\\x06':250,'\\x07':250,'\\x08':250,'\\t':250,'\\n':250,'\\x0b':250,'\\x0c':250,'\\r':250,'\\x0e':250,'\\x0f':250,'\\x10':250,'\\x11':250,'\\x12':250,'\\x13':250,'\\x14':250,'\\x15':250,\r\n '\\x16':250,'\\x17':250,'\\x18':250,'\\x19':250,'\\x1a':250,'\\x1b':250,'\\x1c':250,'\\x1d':250,'\\x1e':250,'\\x1f':250,' ':250,'!':333,'\"':420,'#':500,'$':500,'%':833,'&':778,'\\'':214,'(':333,')':333,'*':500,'+':675,\r\n ',':250,'-':333,'.':250,'/':278,'0':500,'1':500,'2':500,'3':500,'4':500,'5':500,'6':500,'7':500,'8':500,'9':500,':':333,';':333,'<':675,'=':675,'>':675,'?':500,'@':920,'A':611,\r\n 'B':611,'C':667,'D':722,'E':611,'F':611,'G':722,'H':722,'I':333,'J':444,'K':667,'L':556,'M':833,'N':667,'O':722,'P':611,'Q':722,'R':611,'S':500,'T':556,'U':722,'V':611,'W':833,\r\n 'X':611,'Y':556,'Z':556,'[':389,'\\\\':278,']':389,'^':422,'_':500,'`':333,'a':500,'b':500,'c':444,'d':500,'e':444,'f':278,'g':500,'h':500,'i':278,'j':278,'k':444,'l':278,'m':722,\r\n 'n':500,'o':500,'p':500,'q':500,'r':389,'s':389,'t':278,'u':500,'v':444,'w':667,'x':444,'y':444,'z':389,'{':400,'|':275,'}':400,'~':541,'\\x7f':350,'\\x80':500,'\\x81':350,'\\x82':333,'\\x83':500,\r\n '\\x84':556,'\\x85':889,'\\x86':500,'\\x87':500,'\\x88':333,'\\x89':1000,'\\x8a':500,'\\x8b':333,'\\x8c':944,'\\x8d':350,'\\x8e':556,'\\x8f':350,'\\x90':350,'\\x91':333,'\\x92':333,'\\x93':556,'\\x94':556,'\\x95':350,'\\x96':500,'\\x97':889,'\\x98':333,'\\x99':980,\r\n '\\x9a':389,'\\x9b':333,'\\x9c':667,'\\x9d':350,'\\x9e':389,'\\x9f':556,'\\xa0':250,'\\xa1':389,'\\xa2':500,'\\xa3':500,'\\xa4':500,'\\xa5':500,'\\xa6':275,'\\xa7':500,'\\xa8':333,'\\xa9':760,'\\xaa':276,'\\xab':500,'\\xac':675,'\\xad':333,'\\xae':760,'\\xaf':333,\r\n '\\xb0':400,'\\xb1':675,'\\xb2':300,'\\xb3':300,'\\xb4':333,'\\xb5':500,'\\xb6':523,'\\xb7':250,'\\xb8':333,'\\xb9':300,'\\xba':310,'\\xbb':500,'\\xbc':750,'\\xbd':750,'\\xbe':750,'\\xbf':500,'\\xc0':611,'\\xc1':611,'\\xc2':611,'\\xc3':611,'\\xc4':611,'\\xc5':611,\r\n '\\xc6':889,'\\xc7':667,'\\xc8':611,'\\xc9':611,'\\xca':611,'\\xcb':611,'\\xcc':333,'\\xcd':333,'\\xce':333,'\\xcf':333,'\\xd0':722,'\\xd1':667,'\\xd2':722,'\\xd3':722,'\\xd4':722,'\\xd5':722,'\\xd6':722,'\\xd7':675,'\\xd8':722,'\\xd9':722,'\\xda':722,'\\xdb':722,\r\n '\\xdc':722,'\\xdd':556,'\\xde':611,'\\xdf':500,'\\xe0':500,'\\xe1':500,'\\xe2':500,'\\xe3':500,'\\xe4':500,'\\xe5':500,'\\xe6':667,'\\xe7':444,'\\xe8':444,'\\xe9':444,'\\xea':444,'\\xeb':444,'\\xec':278,'\\xed':278,'\\xee':278,'\\xef':278,'\\xf0':500,'\\xf1':500,\r\n '\\xf2':500,'\\xf3':500,'\\xf4':500,'\\xf5':500,'\\xf6':500,'\\xf7':675,'\\xf8':500,'\\xf9':500,'\\xfa':500,'\\xfb':500,'\\xfc':500,'\\xfd':444,'\\xfe':500,'\\xff':444}\r\n\r\nfpdf_charwidths['zapfdingbats']={\r\n '\\x00':0,'\\x01':0,'\\x02':0,'\\x03':0,'\\x04':0,'\\x05':0,'\\x06':0,'\\x07':0,'\\x08':0,'\\t':0,'\\n':0,'\\x0b':0,'\\x0c':0,'\\r':0,'\\x0e':0,'\\x0f':0,'\\x10':0,'\\x11':0,'\\x12':0,'\\x13':0,'\\x14':0,'\\x15':0,\r\n '\\x16':0,'\\x17':0,'\\x18':0,'\\x19':0,'\\x1a':0,'\\x1b':0,'\\x1c':0,'\\x1d':0,'\\x1e':0,'\\x1f':0,' ':278,'!':974,'\"':961,'#':974,'$':980,'%':719,'&':789,'\\'':790,'(':791,')':690,'*':960,'+':939,\r\n ',':549,'-':855,'.':911,'/':933,'0':911,'1':945,'2':974,'3':755,'4':846,'5':762,'6':761,'7':571,'8':677,'9':763,':':760,';':759,'<':754,'=':494,'>':552,'?':537,'@':577,'A':692,\r\n 'B':786,'C':788,'D':788,'E':790,'F':793,'G':794,'H':816,'I':823,'J':789,'K':841,'L':823,'M':833,'N':816,'O':831,'P':923,'Q':744,'R':723,'S':749,'T':790,'U':792,'V':695,'W':776,\r\n 'X':768,'Y':792,'Z':759,'[':707,'\\\\':708,']':682,'^':701,'_':826,'`':815,'a':789,'b':789,'c':707,'d':687,'e':696,'f':689,'g':786,'h':787,'i':713,'j':791,'k':785,'l':791,'m':873,\r\n 'n':761,'o':762,'p':762,'q':759,'r':759,'s':892,'t':892,'u':788,'v':784,'w':438,'x':138,'y':277,'z':415,'{':392,'|':392,'}':668,'~':668,'\\x7f':0,'\\x80':390,'\\x81':390,'\\x82':317,'\\x83':317,\r\n '\\x84':276,'\\x85':276,'\\x86':509,'\\x87':509,'\\x88':410,'\\x89':410,'\\x8a':234,'\\x8b':234,'\\x8c':334,'\\x8d':334,'\\x8e':0,'\\x8f':0,'\\x90':0,'\\x91':0,'\\x92':0,'\\x93':0,'\\x94':0,'\\x95':0,'\\x96':0,'\\x97':0,'\\x98':0,'\\x99':0,\r\n '\\x9a':0,'\\x9b':0,'\\x9c':0,'\\x9d':0,'\\x9e':0,'\\x9f':0,'\\xa0':0,'\\xa1':732,'\\xa2':544,'\\xa3':544,'\\xa4':910,'\\xa5':667,'\\xa6':760,'\\xa7':760,'\\xa8':776,'\\xa9':595,'\\xaa':694,'\\xab':626,'\\xac':788,'\\xad':788,'\\xae':788,'\\xaf':788,\r\n '\\xb0':788,'\\xb1':788,'\\xb2':788,'\\xb3':788,'\\xb4':788,'\\xb5':788,'\\xb6':788,'\\xb7':788,'\\xb8':788,'\\xb9':788,'\\xba':788,'\\xbb':788,'\\xbc':788,'\\xbd':788,'\\xbe':788,'\\xbf':788,'\\xc0':788,'\\xc1':788,'\\xc2':788,'\\xc3':788,'\\xc4':788,'\\xc5':788,\r\n '\\xc6':788,'\\xc7':788,'\\xc8':788,'\\xc9':788,'\\xca':788,'\\xcb':788,'\\xcc':788,'\\xcd':788,'\\xce':788,'\\xcf':788,'\\xd0':788,'\\xd1':788,'\\xd2':788,'\\xd3':788,'\\xd4':894,'\\xd5':838,'\\xd6':1016,'\\xd7':458,'\\xd8':748,'\\xd9':924,'\\xda':748,'\\xdb':918,\r\n '\\xdc':927,'\\xdd':928,'\\xde':928,'\\xdf':834,'\\xe0':873,'\\xe1':828,'\\xe2':924,'\\xe3':924,'\\xe4':917,'\\xe5':930,'\\xe6':931,'\\xe7':463,'\\xe8':883,'\\xe9':836,'\\xea':836,'\\xeb':867,'\\xec':867,'\\xed':696,'\\xee':696,'\\xef':874,'\\xf0':0,'\\xf1':874,\r\n '\\xf2':760,'\\xf3':946,'\\xf4':771,'\\xf5':865,'\\xf6':771,'\\xf7':888,'\\xf8':967,'\\xf9':888,'\\xfa':831,'\\xfb':873,'\\xfc':927,'\\xfd':970,'\\xfe':918,'\\xff':0}\r\n\r\n"},"license":{"kind":"string","value":"gpl-2.0"}}},{"rowIdx":476127,"cells":{"repo_name":{"kind":"string","value":"BaconPancakes/valor"},"path":{"kind":"string","value":"lib/pip/_vendor/colorama/ansitowin32.py"},"copies":{"kind":"string","value":"450"},"size":{"kind":"string","value":"9668"},"content":{"kind":"string","value":"# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nimport re\nimport sys\nimport os\n\nfrom .ansi import AnsiFore, AnsiBack, AnsiStyle, Style\nfrom .winterm import WinTerm, WinColor, WinStyle\nfrom .win32 import windll, winapi_test\n\n\nwinterm = None\nif windll is not None:\n winterm = WinTerm()\n\n\ndef is_stream_closed(stream):\n return not hasattr(stream, 'closed') or stream.closed\n\n\ndef is_a_tty(stream):\n return hasattr(stream, 'isatty') and stream.isatty()\n\n\nclass StreamWrapper(object):\n '''\n Wraps a stream (such as stdout), acting as a transparent proxy for all\n attribute access apart from method 'write()', which is delegated to our\n Converter instance.\n '''\n def __init__(self, wrapped, converter):\n # double-underscore everything to prevent clashes with names of\n # attributes on the wrapped stream object.\n self.__wrapped = wrapped\n self.__convertor = converter\n\n def __getattr__(self, name):\n return getattr(self.__wrapped, name)\n\n def write(self, text):\n self.__convertor.write(text)\n\n\nclass AnsiToWin32(object):\n '''\n Implements a 'write()' method which, on Windows, will strip ANSI character\n sequences from the text, and if outputting to a tty, will convert them into\n win32 function calls.\n '''\n ANSI_CSI_RE = re.compile('\\001?\\033\\[((?:\\d|;)*)([a-zA-Z])\\002?') # Control Sequence Introducer\n ANSI_OSC_RE = re.compile('\\001?\\033\\]((?:.|;)*?)(\\x07)\\002?') # Operating System Command\n\n def __init__(self, wrapped, convert=None, strip=None, autoreset=False):\n # The wrapped stream (normally sys.stdout or sys.stderr)\n self.wrapped = wrapped\n\n # should we reset colors to defaults after every .write()\n self.autoreset = autoreset\n\n # create the proxy wrapping our output stream\n self.stream = StreamWrapper(wrapped, self)\n\n on_windows = os.name == 'nt'\n # We test if the WinAPI works, because even if we are on Windows\n # we may be using a terminal that doesn't support the WinAPI\n # (e.g. Cygwin Terminal). In this case it's up to the terminal\n # to support the ANSI codes.\n conversion_supported = on_windows and winapi_test()\n\n # should we strip ANSI sequences from our output?\n if strip is None:\n strip = conversion_supported or (not is_stream_closed(wrapped) and not is_a_tty(wrapped))\n self.strip = strip\n\n # should we should convert ANSI sequences into win32 calls?\n if convert is None:\n convert = conversion_supported and not is_stream_closed(wrapped) and is_a_tty(wrapped)\n self.convert = convert\n\n # dict of ansi codes to win32 functions and parameters\n self.win32_calls = self.get_win32_calls()\n\n # are we wrapping stderr?\n self.on_stderr = self.wrapped is sys.stderr\n\n def should_wrap(self):\n '''\n True if this class is actually needed. If false, then the output\n stream will not be affected, nor will win32 calls be issued, so\n wrapping stdout is not actually required. This will generally be\n False on non-Windows platforms, unless optional functionality like\n autoreset has been requested using kwargs to init()\n '''\n return self.convert or self.strip or self.autoreset\n\n def get_win32_calls(self):\n if self.convert and winterm:\n return {\n AnsiStyle.RESET_ALL: (winterm.reset_all, ),\n AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),\n AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),\n AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),\n AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),\n AnsiFore.RED: (winterm.fore, WinColor.RED),\n AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),\n AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),\n AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),\n AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),\n AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),\n AnsiFore.WHITE: (winterm.fore, WinColor.GREY),\n AnsiFore.RESET: (winterm.fore, ),\n AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),\n AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),\n AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),\n AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),\n AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),\n AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),\n AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),\n AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),\n AnsiBack.BLACK: (winterm.back, WinColor.BLACK),\n AnsiBack.RED: (winterm.back, WinColor.RED),\n AnsiBack.GREEN: (winterm.back, WinColor.GREEN),\n AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),\n AnsiBack.BLUE: (winterm.back, WinColor.BLUE),\n AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),\n AnsiBack.CYAN: (winterm.back, WinColor.CYAN),\n AnsiBack.WHITE: (winterm.back, WinColor.GREY),\n AnsiBack.RESET: (winterm.back, ),\n AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),\n AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),\n AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),\n AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),\n AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),\n AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),\n AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),\n AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),\n }\n return dict()\n\n def write(self, text):\n if self.strip or self.convert:\n self.write_and_convert(text)\n else:\n self.wrapped.write(text)\n self.wrapped.flush()\n if self.autoreset:\n self.reset_all()\n\n\n def reset_all(self):\n if self.convert:\n self.call_win32('m', (0,))\n elif not self.strip and not is_stream_closed(self.wrapped):\n self.wrapped.write(Style.RESET_ALL)\n\n\n def write_and_convert(self, text):\n '''\n Write the given text to our wrapped stream, stripping any ANSI\n sequences from the text, and optionally converting them into win32\n calls.\n '''\n cursor = 0\n text = self.convert_osc(text)\n for match in self.ANSI_CSI_RE.finditer(text):\n start, end = match.span()\n self.write_plain_text(text, cursor, start)\n self.convert_ansi(*match.groups())\n cursor = end\n self.write_plain_text(text, cursor, len(text))\n\n\n def write_plain_text(self, text, start, end):\n if start < end:\n self.wrapped.write(text[start:end])\n self.wrapped.flush()\n\n\n def convert_ansi(self, paramstring, command):\n if self.convert:\n params = self.extract_params(command, paramstring)\n self.call_win32(command, params)\n\n\n def extract_params(self, command, paramstring):\n if command in 'Hf':\n params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))\n while len(params) < 2:\n # defaults:\n params = params + (1,)\n else:\n params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)\n if len(params) == 0:\n # defaults:\n if command in 'JKm':\n params = (0,)\n elif command in 'ABCD':\n params = (1,)\n\n return params\n\n\n def call_win32(self, command, params):\n if command == 'm':\n for param in params:\n if param in self.win32_calls:\n func_args = self.win32_calls[param]\n func = func_args[0]\n args = func_args[1:]\n kwargs = dict(on_stderr=self.on_stderr)\n func(*args, **kwargs)\n elif command in 'J':\n winterm.erase_screen(params[0], on_stderr=self.on_stderr)\n elif command in 'K':\n winterm.erase_line(params[0], on_stderr=self.on_stderr)\n elif command in 'Hf': # cursor position - absolute\n winterm.set_cursor_position(params, on_stderr=self.on_stderr)\n elif command in 'ABCD': # cursor position - relative\n n = params[0]\n # A - up, B - down, C - forward, D - back\n x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]\n winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)\n\n\n def convert_osc(self, text):\n for match in self.ANSI_OSC_RE.finditer(text):\n start, end = match.span()\n text = text[:start] + text[end:]\n paramstring, command = match.groups()\n if command in '\\x07': # \\x07 = BEL\n params = paramstring.split(\";\")\n # 0 - change title and icon (we will only change title)\n # 1 - change icon (we don't support this)\n # 2 - change title\n if params[0] in '02':\n winterm.set_title(params[1])\n return text\n"},"license":{"kind":"string","value":"gpl-3.0"}}},{"rowIdx":476128,"cells":{"repo_name":{"kind":"string","value":"hypnotika/namebench"},"path":{"kind":"string","value":"libnamebench/site_connector.py"},"copies":{"kind":"string","value":"175"},"size":{"kind":"string","value":"4048"},"content":{"kind":"string","value":"# Copyright 2010 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Class used for connecting to the results site.\"\"\"\n\nimport os\nimport platform\nimport random\nimport socket\nimport sys\nimport tempfile\nimport time\nimport urllib\nimport zlib\n\n# third_party\nimport httplib2\nimport simplejson\n\nimport util\n\nRETRY_WAIT = 10\n\n\nclass SiteConnector(object):\n \"\"\"Methods that connect to the results site.\"\"\"\n\n def __init__(self, config, status_callback=None):\n self.config = config\n self.url = self.config.site_url.rstrip('/')\n self.status_callback = status_callback\n \n def msg(self, msg, count=None, total=None, **kwargs):\n if self.status_callback:\n self.status_callback(msg, count=count, total=total, **kwargs)\n else:\n print '%s [%s/%s]' % (msg, count, total)\n\n def GetIndexHosts(self):\n \"\"\"Get a list of 'index' hosts for standardized testing.\"\"\"\n url = self.url + '/index_hosts'\n h = httplib2.Http(tempfile.gettempdir(), timeout=10)\n content = None\n try:\n unused_resp, content = h.request(url, 'GET')\n hosts = []\n for record_type, host in simplejson.loads(content):\n hosts.append((str(record_type), str(host)))\n return hosts\n except simplejson.decoder.JSONDecodeError:\n self.msg('Failed to decode: \"%s\"' % content)\n return []\n except AttributeError:\n self.msg('%s refused connection' % url)\n return []\n except:\n self.msg('* Failed to fetch %s: %s' % (url, util.GetLastExceptionString()))\n return []\n \n\n def UploadJsonResults(self, json_data, hide_results=False, fail_quickly=False):\n \"\"\"Data is generated by reporter.CreateJsonData.\"\"\"\n\n url = self.url + '/submit'\n if not url or not url.startswith('http'):\n return (False, 'error')\n h = httplib2.Http()\n post_data = {\n 'client_id': self._CalculateDuplicateCheckId(),\n 'submit_id': random.randint(0, 2**32),\n 'hidden': bool(hide_results),\n 'data': json_data\n }\n try:\n resp, content = h.request(url, 'POST', urllib.urlencode(post_data))\n try:\n data = simplejson.loads(content)\n for note in data['notes']:\n print ' * %s' % note\n return (''.join((self.url, data['url'])), data['state'])\n except:\n self.msg('BAD RESPONSE from %s: [%s]:\\n %s' % (url, resp, content))\n print \"DATA:\"\n print post_data\n # See http://code.google.com/p/httplib2/issues/detail?id=62\n except AttributeError:\n self.msg('%s refused connection' % url)\n except:\n self.msg('Error uploading results: %s' % util.GetLastExceptionString())\n\n # We haven't returned, something is up.\n if not fail_quickly:\n self.msg('Problem talking to %s, will retry after %ss' % (url, RETRY_WAIT))\n time.sleep(RETRY_WAIT)\n self.UploadJsonResults(json_data, hide_results=hide_results, fail_quickly=True)\n \n return (False, 'error')\n\n def _CalculateDuplicateCheckId(self):\n \"\"\"This is so that we can detect duplicate submissions from a particular host.\n\n Returns:\n checksum: integer\n \"\"\"\n # From http://docs.python.org/release/2.5.2/lib/module-zlib.html\n # \"not suitable for use as a general hash algorithm.\"\n #\n # We are only using it as a temporary way to detect duplicate runs on the\n # same host in a short time period, so it's accuracy is not important.\n return zlib.crc32(platform.platform() + sys.version + platform.node() +\n os.getenv('HOME', '') + os.getenv('USERPROFILE', ''))\n"},"license":{"kind":"string","value":"apache-2.0"}}},{"rowIdx":476129,"cells":{"repo_name":{"kind":"string","value":"nanobox-io/nanobox-pkgsrc-base"},"path":{"kind":"string","value":"nodejs7/patches/patch-tools_gyp_pylib_gyp_generator_make.py"},"copies":{"kind":"string","value":"16"},"size":{"kind":"string","value":"1181"},"content":{"kind":"string","value":"$NetBSD: patch-tools_gyp_pylib_gyp_generator_make.py,v 1.3 2013/12/12 11:52:37 jperkin Exp $\n\nAdd support for NetBSD and DragonFly.\nEnsure we use the system libtool on OSX.\n\n--- tools/gyp/pylib/gyp/generator/make.py.orig\t2013-12-12 05:20:06.000000000 +0000\n+++ tools/gyp/pylib/gyp/generator/make.py\n@@ -174,7 +174,7 @@ cmd_solink_module = $(LINK.$(TOOLSET)) -\n \n LINK_COMMANDS_MAC = \"\"\"\\\n quiet_cmd_alink = LIBTOOL-STATIC $@\n-cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)\n+cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool /usr/bin/libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)\n \n quiet_cmd_link = LINK($(TOOLSET)) $@\n cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o \"$@\" $(LD_INPUTS) $(LIBS)\n@@ -2012,7 +2012,7 @@ def GenerateOutput(target_list, target_d\n 'flock': './gyp-flock-tool flock',\n 'flock_index': 2,\n })\n- elif flavor == 'freebsd':\n+ elif flavor == 'freebsd' or flavor == 'dragonflybsd' or flavor == 'netbsd':\n # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific.\n header_params.update({\n 'flock': 'lockf',\n"},"license":{"kind":"string","value":"mit"}}},{"rowIdx":476130,"cells":{"repo_name":{"kind":"string","value":"stanlee321/pysolper"},"path":{"kind":"string","value":"latrop/lib/dist/tipfy/template.py"},"copies":{"kind":"string","value":"9"},"size":{"kind":"string","value":"21622"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A simple template system that compiles templates to Python code.\n\nBasic usage looks like:\n\n t = template.Template(\"{{ myvalue }}\")\n print t.generate(myvalue=\"XXX\")\n\nLoader is a class that loads templates from a root directory and caches\nthe compiled templates:\n\n loader = template.Loader(\"/home/btaylor\")\n print loader.load(\"test.html\").generate(myvalue=\"XXX\")\n\nWe compile all templates to raw Python. Error-reporting is currently... uh,\ninteresting. Syntax for the templates\n\n ### base.html\n \n
\n
\n \n
\n