Example #1
0
 def test_file_owner(self):
   new_owner = 'newowner'
   self.client.write('foo', 'hello, world!')
   self.client.set_owner('foo', 'oldowner')
   self.client.set_owner('foo', new_owner)
   status = self.client.status('foo')
   eq_(status['owner'], new_owner)
 def test_with_oddly_formatted_composer_file(self):
     exts = self.extension_module.ComposerConfiguration({
         'BUILD_DIR': ''
     }).read_exts_from_path(
         'tests/data/composer/composer-format.json')
     eq_(1, len(exts))
     eq_('mysqli', exts[0])
Example #3
0
 def test_valid_disabled_snippet_authenticated(self):
     """Test disabled snippet returns 200 to authenticated users."""
     snippet = SnippetFactory.create(disabled=True)
     User.objects.create_superuser('admin', 'admin@example.com', 'asdf')
     self.client.login(username='admin', password='asdf')
     response = self.client.get(reverse('base.show', kwargs={'snippet_id': snippet.id}))
     eq_(response.status_code, 200)
Example #4
0
def test_sample_info_genotype():
    variants = load_vcf(data_path("multiallelic.vcf"))
    assert len(variants) == 2, "Expected 2 variants but got %s" % variants
    eq_(variants.metadata[variants[0]]['sample_info']['metastasis']['GT'],
        '0/1')
    eq_(variants.metadata[variants[1]]['sample_info']['metastasis']['GT'],
        '0/1')
Example #5
0
    def __test(hop_length, fmin, n_bins, bins_per_octave,
               tuning, resolution, norm, sparsity):

        C2 = librosa.hybrid_cqt(y, sr=sr,
                                hop_length=hop_length,
                                fmin=fmin, n_bins=n_bins,
                                bins_per_octave=bins_per_octave,
                                tuning=tuning, resolution=resolution,
                                norm=norm,
                                sparsity=sparsity)

        C1 = librosa.cqt(y, sr=sr,
                         hop_length=hop_length,
                         fmin=fmin, n_bins=n_bins,
                         bins_per_octave=bins_per_octave,
                         tuning=tuning, resolution=resolution,
                         norm=norm,
                         sparsity=sparsity)

        eq_(C1.shape, C2.shape)

        # Check for numerical comparability
        idx1 = (C1 > 1e-4 * C1.max())
        idx2 = (C2 > 1e-4 * C2.max())

        perc = 0.99

        thresh = 1e-3

        idx = idx1 | idx2

        assert np.percentile(np.abs(C1[idx] - C2[idx]),
                             perc) < thresh * max(C1.max(), C2.max())
Example #6
0
    def test_channel_edit_child(self):
        channel = Channel.objects.get(slug='testing')
        response = self.client.get(
            reverse('manage:channel_edit', args=(channel.pk,)),
        )
        eq_(response.status_code, 200)
        choices = (
            response.content
            .split('name="parent"')[1]
            .split('</select>')[0]
        )
        ok_('Main' in choices)
        # you should not be able to self-reference
        ok_('Testing' not in choices)

        main = Channel.objects.get(slug='main')
        response = self.client.post(
            reverse('manage:channel_edit', args=(channel.pk,)),
            {
                'name': 'Different',
                'slug': 'different',
                'description': '<p>Other things</p>',
                'parent': main.pk,
                'feed_size': 10,
            }
        )
        eq_(response.status_code, 302)
        channel = Channel.objects.get(slug='different')
        eq_(channel.parent, main)

        # now expect two links to "Main" on the channels page
        response = self.client.get(reverse('manage:channels'))
        eq_(response.status_code, 200)
        view_url = reverse('main:home_channels', args=(main.slug,))
        eq_(response.content.count(view_url), 2)
Example #7
0
 def test_file_size(self):
     self.viewer.extract()
     self.viewer.get_files()
     self.viewer.select('install.js')
     res = self.viewer.read_file()
     eq_(res, '')
     assert self.viewer.selected['msg'].startswith('File size is')
Example #8
0
 def test_solid_paletted_image(self):
     img = Image.new('P', (100, 100), color=20)
     palette = []
     for i in range(256):
         palette.extend((i, i//2, i%3))
     img.putpalette(palette)
     eq_(is_single_color_image(img), (20, 10, 2))
Example #9
0
 def test_from_paletted(self):
     img = self._make_test_image().quantize(256)
     img = make_transparent(img, (130, 150, 120), tolerance=5)
     assert img.mode == 'RGBA'
     assert img.size == (50, 50)
     colors = img.getcolors()
     eq_(colors, [(1600, (130, 140, 120, 255)), (900, (130, 150, 120, 0))])
Example #10
0
 def test_seek_iter(self):
     self.rbuf_wrapper.seek(0)
     data = list(self.rbuf_wrapper)
     eq_(data, ['Hello World!'])
     self.rbuf_wrapper.seek(0)
     data = list(self.rbuf_wrapper)
     eq_(data, ['Hello World!'])
Example #11
0
 def test_solid_merge(self):
     img1 = ImageSource(Image.new('RGB', (10, 10), (255, 0, 255)))
     img2 = ImageSource(Image.new('RGB', (10, 10), (0, 255, 255)))
     
     result = merge_images([img1, img2], ImageOptions(transparent=False))
     img = result.as_image()
     eq_(img.getpixel((0, 0)), (0, 255, 255))
Example #12
0
 def test_dir_with_status(self):
   self.client.write('foo/bar', 'hello, world!')
   statuses = self.client.list('foo', status=True)
   eq_(len(statuses), 1)
   status = self.client.status('foo/bar')
   status['pathSuffix'] = 'bar'
   eq_(statuses[0], ('bar', status))
Example #13
0
 def test_file_for_group(self):
   new_group = 'newgroup'
   self.client.write('foo', 'hello, world!')
   self.client.set_owner('foo', group='oldgroup')
   self.client.set_owner('foo', group=new_group)
   status = self.client.status('foo')
   eq_(status['group'], new_group)
Example #14
0
 def test_directory_for_group(self):
   new_group = 'newgroup'
   self.client._mkdirs('foo')
   self.client.set_owner('foo', group='oldgroup')
   self.client.set_owner('foo', group=new_group)
   status = self.client.status('foo')
   eq_(status['group'], new_group)
    def test_current_versions(self, rget):
        model = models.CurrentVersions
        api = model()

        def mocked_get(**options):
            assert '/products/' in options['url']
            return Response("""
                {"hits": {
                   "SeaMonkey": [{
                     "product": "SeaMonkey",
                     "throttle": "100.00",
                     "end_date": "2012-05-10 00:00:00",
                     "start_date": "2012-03-08 00:00:00",
                     "featured": true,
                     "version": "2.1.3pre",
                     "release": "Beta",
                     "id": 922}]
                  },
                  "products": ["SeaMonkey"]
                }
              """)

        rget.side_effect = mocked_get
        info = api.get()
        ok_(isinstance(info, list))
        ok_(isinstance(info[0], dict))
        eq_(info[0]['product'], 'SeaMonkey')
Example #16
0
 def test_some_pin(self):
     self.solitude.generic.buyer.get_object_or_404.return_value = {
         'pin': True}
     res = self.client.get(self.url)
     self.solitude.generic.buyer.get_object_or_404.assert_called_with(
         headers={}, uuid='a')
     eq_(json.loads(res.content)['pin'], True)
    def test_correlations_signatures(self, rget):
        model = models.CorrelationsSignatures
        api = model()

        def mocked_get(url, **options):
            assert '/correlations/signatures' in url
            ok_('/report_type/core-counts' in url)
            return Response("""
            {
                "hits": ["FakeSignature1",
                         "FakeSignature2"],
                "total": 2
            }
        """)

        rget.side_effect = mocked_get
        r = api.get(report_type='core-counts',
                    product='WaterWolf',
                    version='1.0a1',
                    platforms=['Windows NT', 'Linux'])
        eq_(r['total'], 2)
        r = api.get(report_type='core-counts',
                    product='WaterWolf',
                    version='1.0a1')
        eq_(r['total'], 2)
Example #18
0
 def test_no_user(self):
     self.solitude.generic.buyer.get_object_or_404.side_effect = (
         ObjectDoesNotExist)
     res = self.client.post(self.url, {'pin': '1234'})
     self.solitude.generic.buyer.post.assert_called_with({'uuid': 'a',
                                                          'pin': '1234'})
     eq_(res.status_code, 201)
Example #19
0
 def test_bom(self):
     dest = os.path.join(settings.TMP_PATH, 'test_bom')
     open(dest, 'w').write('foo'.encode('utf-16'))
     self.viewer.select('foo')
     self.viewer.selected = {'full': dest, 'size': 1}
     eq_(self.viewer.read_file(), u'foo')
     os.remove(dest)
Example #20
0
 def test_py_lang_files_defined(self):
     """
     If `LANG_FILES` is defined a list of the values should be returned.
     """
     lang_files = langfiles_for_path('lib/l10n_utils/tests/test_files/'
                                     'extract_me_with_langfiles.py')
     eq_(lang_files, ['lebowski', 'dude'])
Example #21
0
 def test_delete_mid_read(self):
     self.viewer.extract()
     self.viewer.select('install.js')
     os.remove(os.path.join(self.viewer.dest, 'install.js'))
     res = self.viewer.read_file()
     eq_(res, '')
     assert self.viewer.selected['msg'].startswith('That file no')
Example #22
0
 def test_composer_tool_install_latest(self):
     ctx = utils.FormattedDict(
         {
             "PHP_VM": "will_default_to_php_strategy",
             "BUILD_DIR": "/build/dir",
             "CACHE_DIR": "/cache/dir",
             "COMPOSER_VERSION": "latest",
             "BP_DIR": "",
             "WEBDIR": "",
         }
     )
     builder = Dingus(_ctx=ctx)
     installer = Dingus()
     cfInstaller = Dingus()
     builder.install = Dingus(_installer=cfInstaller, return_value=installer)
     ct = self.extension_module.ComposerExtension(ctx)
     ct._builder = builder
     ct.install()
     eq_(2, len(builder.install.calls()))
     # make sure PHP is installed
     assert installer.package.calls().once()
     eq_("PHP", installer.package.calls()[0].args[0])
     call = installer.package.calls()[0]
     assert call.return_value.calls().once()
     assert installer.calls().once()
     # make sure composer is installed
     assert installer._installer.calls().once()
     assert installer._installer.calls()[0].args[0] == "https://getcomposer.org/composer.phar", (
         "was %s" % installer._installer.calls()[0].args[0]
     )
Example #23
0
    def test_answer_welcome_email(self):
        u1 = profile().user
        u2 = profile(first_answer_email_sent=True).user
        u3 = profile().user

        two_days = datetime.now() - timedelta(hours=48)

        q = question(creator=u1, save=True)
        answer(question=q, creator=u1, created=two_days, save=True)
        answer(question=q, creator=u2, created=two_days, save=True)
        answer(question=q, creator=u3, created=two_days, save=True)

        # Clear out the notifications that were sent
        mail.outbox = []
        # Send email(s) for welcome messages
        cron.send_welcome_emails()

        # There should be an email for u3 only.
        # u1 was the asker, and so did not make a contribution.
        # u2 has already recieved the email

        eq_(len(mail.outbox), 1)
        attrs_eq(mail.outbox[0], to=[u3.email])

        # u3's flag should now be set.
        u3 = User.objects.get(id=u3.id)
        eq_(u3.profile.first_answer_email_sent, True)
Example #24
0
def test_combined_inputs():
    foo = '<a><b>foo</b></a>'
    bar = '<a><b>bar</b></a>'

    result = combined_inputs([foo, bar])
    result = etree.tostring(result)
    eq_(result, b'<a><b>foo</b><b>bar</b></a>')
Example #25
0
def test_pipeline_empty():
    """Pipelines should be empty after a send() call."""
    sc = _client()
    with sc.pipeline() as pipe:
        pipe.incr('foo')
        eq_(1, len(pipe._stats))
    eq_(0, len(pipe._stats))
Example #26
0
 def test_from_revision_none(self):
     rev = revision()
     try:
         diff = revisions_unified_diff(None, rev)
     except AttributeError:
         self.fail("Should not throw AttributeError")
     eq_("Diff is unavailable.", diff)
 def test_composer_tool_install_latest(self):
     ctx = utils.FormattedDict({
         'DOWNLOAD_URL': 'http://server/bins',
         'PHP_VM': 'will_default_to_php_strategy',
         'BUILD_DIR': '/build/dir',
         'CACHE_DIR': '/cache/dir',
         'COMPOSER_VERSION': 'latest',
         'BP_DIR': ''
     })
     builder = Dingus(_ctx=ctx)
     installer = Dingus()
     cfInstaller = Dingus()
     builder.install = Dingus(_installer=cfInstaller,
                              return_value=installer)
     ct = self.extension_module.ComposerExtension(ctx)
     ct._builder = builder
     ct.install()
     eq_(2, len(builder.install.calls()))
     # make sure PHP is installed
     assert installer.package.calls().once()
     eq_('PHP', installer.package.calls()[0].args[0])
     call = installer.package.calls()[0]
     assert call.return_value.calls().once()
     assert installer.calls().once()
     # make sure composer is installed
     assert installer._installer.calls().once()
     assert installer._installer.calls()[0].args[0] == \
         'https://getcomposer.org/composer.phar', \
         "was %s" % installer._installer.calls()[0].args[0]
    def test_signature_urls(self, rget):
        model = models.SignatureURLs
        api = model()

        def mocked_get(**options):
            assert '/signatureurls/' in options['url']
            ok_(urllib.quote('WaterWolf:1.0') in options['url'])
            return Response("""{
                "hits": [{"url": "http://farm.ville", "crash_count":123}],
                "total": 1
            }
            """)

        rget.side_effect = mocked_get
        today = datetime.datetime.utcnow()
        response = api.get(
            signature='FakeSignature',
            products=['WaterWolf'],
            versions=['WaterWolf:1.0'],
            start_date=today - datetime.timedelta(days=1),
            end_date=today,
        )
        eq_(response['total'], 1)
        eq_(response['hits'][0], {'url': 'http://farm.ville',
                                  'crash_count': 123})
Example #29
0
    def test_flag_on(self):
        Flag.objects.create(name='serve_pregenerated_snippets', everyone=True)

        with patch.object(views, 'fetch_pregenerated_snippets') as fetch_pregenerated_snippets:
            eq_(views.fetch_snippets(self.request, foo='bar'),
                fetch_pregenerated_snippets.return_value)
            fetch_pregenerated_snippets.assert_called_with(self.request, foo='bar')
Example #30
0
 def test_directory_owner(self):
   new_owner = 'newowner'
   self.client._mkdirs('foo')
   self.client.set_owner('foo', 'oldowner')
   self.client.set_owner('foo', new_owner)
   status = self.client.status('foo')
   eq_(status['owner'], new_owner)