How to use not_binary method in gabbi

Best Python code snippet using gabbi_python

test_views.py

Source:test_views.py Github

copy

Full Screen

1import json2import os3import urlparse4from django.conf import settings5from django.core.cache import cache6from django.core.urlresolvers import reverse7from django.utils.http import http_date8from cache_nuggets.lib import Message9from mock import patch10from nose import SkipTest11from nose.tools import eq_12from pyquery import PyQuery as pq13import mkt14import mkt.site.tests15from mkt.files.helpers import DiffHelper, FileViewer16from mkt.files.models import File17from mkt.site.fixtures import fixture18from mkt.site.storage_utils import (copy_stored_file, local_storage,19 private_storage, public_storage)20from mkt.users.models import UserProfile21from mkt.webapps.models import Webapp22packaged_app = 'mkt/submit/tests/packaged/full-tpa.zip'23not_binary = 'script.js'24binary = 'icons/256.png'25class FilesBase(object):26 def login_as_editor(self):27 self.login('editor@mozilla.com')28 def setUp(self):29 self.app = Webapp.objects.get(pk=337141)30 self.app.update(is_packaged=True, status=mkt.WEBAPPS_UNREVIEWED_STATUS)31 self.dev = self.app.authors.all()[0]32 self.regular = UserProfile.objects.get(pk=999)33 self.version = self.app.versions.latest()34 self.file = self.version.all_files[0]35 self.versions = [self.version,36 self.app.versions.create(37 version='%s.1' % self.version.version)]38 self.files = [self.file,39 File.objects.create(version=self.versions[1],40 filename='webapp.zip')]41 self.login_as_editor()42 for file_obj in self.files:43 src = os.path.join(settings.ROOT, packaged_app)44 if file_obj.status in mkt.LISTED_STATUSES:45 target = public_storage46 else:47 target = private_storage48 copy_stored_file(src, file_obj.file_path,49 src_storage=local_storage,50 dst_storage=target)51 self.file_viewer = FileViewer(self.file)52 def tearDown(self):53 self.file_viewer.cleanup()54 def files_redirect(self, file):55 return reverse('mkt.files.redirect', args=[self.file.pk, file])56 def files_serve(self, file):57 return reverse('mkt.files.serve', args=[self.file.pk, file])58 def test_view_access_anon(self):59 self.client.logout()60 self.check_urls(403)61 def test_view_access_editor(self):62 self.file_viewer.extract()63 self.check_urls(200)64 def test_view_access_developer(self):65 self.client.logout()66 self.login(self.dev.email)67 self.file_viewer.extract()68 self.check_urls(200)69 def test_view_access_another_developer(self):70 self.client.logout()71 self.login(self.regular.email)72 self.file_viewer.extract()73 self.check_urls(403)74 def test_poll_extracted(self):75 self.file_viewer.extract()76 res = self.client.get(self.poll_url())77 eq_(res.status_code, 200)78 eq_(json.loads(res.content)['status'], True)79 def test_poll_not_extracted(self):80 res = self.client.get(self.poll_url())81 eq_(res.status_code, 200)82 eq_(json.loads(res.content)['status'], False)83 def test_poll_extracted_anon(self):84 self.client.logout()85 res = self.client.get(self.poll_url())86 eq_(res.status_code, 403)87 def test_content_headers(self):88 self.file_viewer.extract()89 res = self.client.get(self.file_url('manifest.webapp'))90 assert 'etag' in res._headers91 assert 'last-modified' in res._headers92 def test_content_headers_etag(self):93 self.file_viewer.extract()94 self.file_viewer.select('manifest.webapp')95 obj = getattr(self.file_viewer, 'left', self.file_viewer)96 etag = obj.selected.get('md5')97 res = self.client.get(self.file_url('manifest.webapp'),98 HTTP_IF_NONE_MATCH=etag)99 eq_(res.status_code, 304)100 def test_content_headers_if_modified(self):101 self.file_viewer.extract()102 self.file_viewer.select('manifest.webapp')103 obj = getattr(self.file_viewer, 'left', self.file_viewer)104 date = http_date(obj.selected.get('modified'))105 res = self.client.get(self.file_url('manifest.webapp'),106 HTTP_IF_MODIFIED_SINCE=date)107 eq_(res.status_code, 304)108 def test_file_header(self):109 self.file_viewer.extract()110 res = self.client.get(self.file_url(not_binary))111 eq_(res.status_code, 200)112 url = res.context['file_link']['url']113 eq_(url, reverse('reviewers.apps.review', args=[self.app.app_slug]))114 def test_content_no_file(self):115 self.file_viewer.extract()116 res = self.client.get(self.file_url())117 doc = pq(res.content)118 eq_(len(doc('#content')), 0)119 def test_no_files(self):120 self.file_viewer.cleanup()121 res = self.client.get(self.file_url())122 eq_(res.status_code, 200)123 assert 'files' in res.context124 def test_files(self):125 self.file_viewer.extract()126 res = self.client.get(self.file_url())127 eq_(res.status_code, 200)128 assert 'files' in res.context129 def test_files_anon(self):130 self.client.logout()131 res = self.client.get(self.file_url())132 eq_(res.status_code, 403)133 def test_files_file(self):134 self.file_viewer.extract()135 res = self.client.get(self.file_url(not_binary))136 eq_(res.status_code, 200)137 assert 'selected' in res.context138 def test_files_back_link(self):139 self.file_viewer.extract()140 res = self.client.get(self.file_url(not_binary))141 doc = pq(res.content)142 eq_(doc('#commands td')[-1].text_content(), 'Back to review')143 def test_diff_redirect(self):144 ids = self.files[0].id, self.files[1].id145 res = self.client.post(self.file_url(),146 {'left': ids[0], 'right': ids[1]})147 eq_(res.status_code, 302)148 self.assert3xx(res, reverse('mkt.files.compare', args=ids))149 def test_browse_redirect(self):150 ids = self.files[0].id,151 res = self.client.post(self.file_url(), {'left': ids[0]})152 eq_(res.status_code, 302)153 self.assert3xx(res, reverse('mkt.files.list', args=ids))154 def test_browse_deleted_version(self):155 self.file.version.delete()156 res = self.client.post(self.file_url(), {'left': self.file.id})157 eq_(res.status_code, 404)158 def test_file_chooser(self):159 res = self.client.get(self.file_url())160 doc = pq(res.content)161 left = doc('#id_left')162 eq_(len(left), 1)163 vers = left('option')164 eq_(len(vers), 3)165 # Only one file per version on Marketplace for the time being.166 eq_(vers.eq(0).text(), '')167 f = self.versions[1].all_files[0]168 eq_(vers.eq(1).text(), '%s (%s)' % (self.versions[1].version,169 mkt.STATUS_CHOICES_API[f.status]))170 f = self.versions[0].all_files[0]171 eq_(vers.eq(2).text(), '%s (%s)' % (self.versions[0].version,172 mkt.STATUS_CHOICES_API[f.status]))173class TestFileViewer(FilesBase, mkt.site.tests.WebappTestCase):174 fixtures = fixture('group_editor', 'user_editor', 'user_editor_group',175 'user_999', 'webapp_337141')176 def poll_url(self):177 return reverse('mkt.files.poll', args=[self.file.pk])178 def file_url(self, file=None):179 args = [self.file.pk]180 if file:181 args.extend(['file', file])182 return reverse('mkt.files.list', args=args)183 def check_urls(self, status):184 for url in [self.poll_url(), self.file_url()]:185 status_code = self.client.get(url).status_code186 assert status_code == status, (187 'Request to %s returned status code %d (expected %d)' %188 (url, status_code, status))189 def add_file(self, name, contents):190 dest = os.path.join(self.file_viewer.dest, name)191 with private_storage.open(dest, 'w') as f:192 f.write(contents)193 def test_files_xss(self):194 self.file_viewer.extract()195 self.add_file('<script>alert("foo")', '.')196 res = self.client.get(self.file_url())197 eq_(res.status_code, 200)198 doc = pq(res.content)199 # Note: this is text, not a DOM element, so escaped correctly.200 assert '<script>alert("' in doc('#files li a').text()201 def test_content_file(self):202 self.file_viewer.extract()203 res = self.client.get(self.file_url('manifest.webapp'))204 doc = pq(res.content)205 eq_(len(doc('#content')), 1)206 def test_content_no_file(self):207 self.file_viewer.extract()208 res = self.client.get(self.file_url())209 doc = pq(res.content)210 eq_(len(doc('#content')), 1)211 eq_(res.context['key'], 'manifest.webapp')212 def test_content_xss(self):213 self.file_viewer.extract()214 for name in ['file.txt', 'file.html', 'file.htm']:215 # If you are adding files, you need to clear out the memcache216 # file listing.217 cache.clear()218 self.add_file(name, '<script>alert("foo")</script>')219 res = self.client.get(self.file_url(name))220 doc = pq(res.content)221 # Note: this is text, not a DOM element, so escaped correctly.222 assert doc('#content').text().startswith('<script')223 def test_binary(self):224 self.file_viewer.extract()225 self.add_file('file.php', '<script>alert("foo")</script>')226 res = self.client.get(self.file_url('file.php'))227 eq_(res.status_code, 200)228 assert self.file_viewer.get_files()['file.php']['md5'] in res.content229 def test_tree_no_file(self):230 self.file_viewer.extract()231 res = self.client.get(self.file_url('doesnotexist.js'))232 eq_(res.status_code, 404)233 def test_directory(self):234 self.file_viewer.extract()235 res = self.client.get(self.file_url('doesnotexist.js'))236 eq_(res.status_code, 404)237 def test_serve_no_token(self):238 self.file_viewer.extract()239 res = self.client.get(self.files_serve(binary))240 eq_(res.status_code, 403)241 def test_serve_fake_token(self):242 self.file_viewer.extract()243 res = self.client.get(self.files_serve(binary) + '?token=aasd')244 eq_(res.status_code, 403)245 def test_serve_bad_token(self):246 self.file_viewer.extract()247 res = self.client.get(self.files_serve(binary) + '?token=a asd')248 eq_(res.status_code, 403)249 def test_serve_get_token(self):250 self.file_viewer.extract()251 res = self.client.get(self.files_redirect(binary))252 eq_(res.status_code, 302)253 url = res['Location']254 assert url.startswith(settings.STATIC_URL)255 assert urlparse.urlparse(url).query.startswith('token=')256 def test_memcache_goes_bye_bye(self):257 self.file_viewer.extract()258 res = self.client.get(self.files_redirect(binary))259 url = res['Location'][len(settings.STATIC_URL) - 1:]260 cache.clear()261 res = self.client.get(url)262 eq_(res.status_code, 403)263 def test_bounce(self):264 # Don't run this test if the server has x-sendfile turned off.265 if not settings.XSENDFILE:266 raise SkipTest()267 self.file_viewer.extract()268 res = self.client.get(self.files_redirect(binary), follow=True)269 eq_(res.status_code, 200)270 eq_(res[settings.XSENDFILE_HEADER],271 self.file_viewer.get_files().get(binary)['full'])272 @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)273 def test_file_size(self):274 self.file_viewer.extract()275 res = self.client.get(self.file_url(not_binary))276 doc = pq(res.content)277 assert doc('.error').text().startswith('File size is')278 def test_poll_failed(self):279 msg = Message('file-viewer:%s' % self.file_viewer)280 msg.save('I like cheese.')281 res = self.client.get(self.poll_url())282 eq_(res.status_code, 200)283 data = json.loads(res.content)284 eq_(data['status'], False)285 eq_(data['msg'], ['I like cheese.'])286 def test_file_chooser_selection(self):287 res = self.client.get(self.file_url())288 doc = pq(res.content)289 eq_(doc('#id_left option[selected]').attr('value'),290 str(self.files[0].id))291 eq_(len(doc('#id_right option[value][selected]')), 0)292class TestDiffViewer(FilesBase, mkt.site.tests.WebappTestCase):293 fixtures = fixture('group_editor', 'user_editor', 'user_editor_group',294 'user_999', 'webapp_337141')295 def setUp(self):296 super(TestDiffViewer, self).setUp()297 self.file_viewer = DiffHelper(self.files[0], self.files[1])298 def poll_url(self):299 return reverse('mkt.files.compare.poll', args=[self.files[0].pk,300 self.files[1].pk])301 def add_file(self, file_obj, name, contents):302 dest = os.path.join(file_obj.dest, name)303 with private_storage.open(dest, 'w') as f:304 f.write(contents)305 def file_url(self, file=None):306 args = [self.files[0].pk, self.files[1].pk]307 if file:308 args.extend(['file', file])309 return reverse('mkt.files.compare', args=args)310 def check_urls(self, status):311 for url in [self.poll_url(), self.file_url()]:312 status_code = self.client.get(url).status_code313 assert status_code == status, (314 'Request to %s returned status code %d (expected %d)' %315 (url, status_code, status))316 def test_tree_no_file(self):317 self.file_viewer.extract()318 res = self.client.get(self.file_url('doesnotexist.js'))319 eq_(res.status_code, 404)320 def test_content_file(self):321 self.file_viewer.extract()322 res = self.client.get(self.file_url(not_binary))323 doc = pq(res.content)324 eq_(len(doc('pre')), 3)325 def test_binary_serve_links(self):326 self.file_viewer.extract()327 res = self.client.get(self.file_url(binary))328 doc = pq(res.content)329 node = doc('#content-wrapper a')330 eq_(len(node), 2)331 assert node[0].text.startswith('Download 256.png')332 def test_view_both_present(self):333 self.file_viewer.extract()334 res = self.client.get(self.file_url(not_binary))335 doc = pq(res.content)336 eq_(len(doc('pre')), 3)337 eq_(len(doc('#content-wrapper p')), 4)338 def test_view_one_missing(self):339 self.file_viewer.extract()340 private_storage.delete(os.path.join(self.file_viewer.right.dest,341 'script.js'))342 res = self.client.get(self.file_url(not_binary))343 doc = pq(res.content)344 eq_(len(doc('pre')), 3)345 eq_(len(doc('#content-wrapper p')), 2)346 def test_view_left_binary(self):347 self.file_viewer.extract()348 filename = os.path.join(self.file_viewer.left.dest, 'script.js')349 with private_storage.open(filename, 'w') as f:350 f.write('MZ')351 res = self.client.get(self.file_url(not_binary))352 assert 'This file is not viewable online' in res.content353 def test_view_right_binary(self):354 self.file_viewer.extract()355 filename = os.path.join(self.file_viewer.right.dest, 'script.js')356 with private_storage.open(filename, 'w') as f:357 f.write('MZ')358 assert not self.file_viewer.is_diffable()359 res = self.client.get(self.file_url(not_binary))360 assert 'This file is not viewable online' in res.content361 def test_different_tree(self):362 self.file_viewer.extract()363 private_storage.delete(os.path.join(self.file_viewer.left.dest,364 not_binary))365 res = self.client.get(self.file_url(not_binary))366 doc = pq(res.content)367 eq_(doc('h4:last').text(), 'Deleted files:')368 eq_(len(doc('ul.root')), 2)369 def test_file_chooser_selection(self):370 res = self.client.get(self.file_url())371 doc = pq(res.content)372 eq_(doc('#id_left option[selected]').attr('value'),373 str(self.files[0].id))374 eq_(doc('#id_right option[selected]').attr('value'),...

Full Screen

Full Screen

day_07.py

Source:day_07.py Github

copy

Full Screen

1"""Advent of Code Day 7 - Some Assembly Required"""2import re3def attempt(instruction):4 """Parses and attempts instruction returning True only if successful."""5 # Parse instruction6 target_regex = re.compile(r'-> (\w+)')7 target_wire = target_regex.search(instruction).group(1)8 not_regex = re.compile(r'NOT (\w+) ->')9 connection_regex = re.compile(r'(\S+) ->')10 gapped_regex = re.compile(r'(\w+) (AND|OR|LSHIFT|RSHIFT) (\S+) ->')11 if not_regex.search(instruction):12 wire_value = wires[not_regex.search(instruction).group(1)]13 binary_value = bin(wire_value)[2:].zfill(16)14 not_binary = ''15 for bit in binary_value:16 if bit == '1':17 not_binary += '0'18 else:19 not_binary += '1'20 value = int(not_binary, 2)21 elif gapped_regex.search(instruction):22 first = gapped_regex.search(instruction).group(1)23 operation = gapped_regex.search(instruction).group(2)24 second = gapped_regex.search(instruction).group(3)25 if first.isnumeric():26 first_comp = int(first)27 else:28 first_comp = wires[first]29 if second.isnumeric():30 second_comp = int(second)31 else:32 second_comp = wires[second]33 if operation == 'LSHIFT':34 value = first_comp << second_comp35 elif operation == 'RSHIFT':36 value = first_comp >> second_comp37 elif operation == 'AND':38 value = first_comp & second_comp39 elif operation == 'OR':40 value = first_comp | second_comp41 elif connection_regex.search(instruction):42 new_value = connection_regex.search(instruction).group(1)43 if new_value.isnumeric():44 value = new_value45 else:46 value = wires[new_value]47 try:48 wires[target_wire] = int(value)49 except:50 return51 return True52with open('inputs/day_07.txt') as f:53 instructions = f.readlines()54wires = {}55while instructions:56 completed = []57 for instruction in instructions:58 # Catch instructions that aren't yet possible and continue past them59 try:60 if attempt(instruction):61 completed.append(instruction)62 except:63 continue64 # Remove completed instructions after cycle so iteration works properly65 for done in completed:66 instructions.remove(done)67# Answer One68print("Answer One =", wires['a'])69# Part Two70new_b = wires['a']71wires = {'b': new_b,}72with open('inputs/day_07.txt') as f:73 instructions = f.readlines()74while instructions:75 completed = []76 for instruction in instructions:77 # Override the instruction which sets wire b to keep it at required value78 if instruction == "14146 -> b\n":79 completed.append(instruction)80 continue81 try:82 if attempt(instruction):83 completed.append(instruction)84 except:85 continue86 for done in completed:87 instructions.remove(done)88# Answer Two...

Full Screen

Full Screen

Day7.py

Source:Day7.py Github

copy

Full Screen

1""" Day 7: Some assembly required """2import re3def instruction_execution(instruction):4 target_regex = re.compile(r'-> (\S+)')5 target_wire = target_regex.search(instruction).group(1)6 not_regex = re.compile(r'NOT (\S+) ->')7 connection_regex = re.compile(r'(\S+) ->')8 logical_regex = re.compile(r'(\S+) (AND|OR|LSHIFT|RSHIFT) (\S+) ->')9 if logical_regex.search(instruction):10 first = logical_regex.search(instruction).group(1)11 operation = logical_regex.search(instruction).group(2)12 second = logical_regex.search(instruction).group(3)13 if first.isnumeric():14 first_comp = int(first)15 else:16 first_comp = wires[first]17 if second.isnumeric():18 second_comp = int(second)19 else:20 second_comp = wires[second]21 if operation == 'LSHIFT':22 value = first_comp << second_comp23 elif operation == 'RSHIFT':24 value = first_comp >> second_comp25 elif operation == 'AND':26 value = first_comp & second_comp27 elif operation == 'OR':28 value = first_comp | second_comp29 elif not_regex.search(instruction):30 wire_value = wires[not_regex.search(instruction).group(1)]31 binary_value = bin(wire_value)[2:].zfill(16)32 not_binary = ''33 for bit in binary_value:34 if bit == '1':35 not_binary += '0'36 else:37 not_binary += '1'38 value = int(not_binary,2)39 elif connection_regex.search(instruction):40 new_value = connection_regex.search(instruction).group(1)41 if new_value.isnumeric():42 value = new_value43 else:44 value = wires[new_value]45 46 try:47 wires[target_wire] = int(value)48 except:49 return50 return True51with open('input_d7.txt') as f:52 instructions = f.readlines()53wires = {}54while instructions:55 completed = []56 for instruction in instructions:57 try:58 if instruction_execution(instruction):59 completed.append(instruction)60 except:61 continue62 for done in completed:63 instructions.remove(done)64print("Part one answer: ", wires['a'])65""" Part two """66new_b = wires['a']67wires = {'b': new_b,}68with open('input_d7.txt') as f:69 instructions = f.readlines()70while instructions:71 completed = []72 for instruction in instructions:73 # Override the instruction which sets wire b to keep it at required value74 if instruction == "19138 -> b\n":75 completed.append(instruction)76 continue77 try:78 if instruction_execution(instruction):79 completed.append(instruction)80 except:81 continue82 for done in completed:83 instructions.remove(done)84# Answer Two...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run gabbi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful