Best Python code snippet using slash
test_integration.py
Source:test_integration.py
1import unittest2import json3import os4import textwrap5from open_captcha.common_types import ServerContext, RenderingOptions6from open_captcha.captcha_generator import CaptchaGenerator7from open_captcha.challenge_templates import render_bar_chart8class IntegrationTest(unittest.TestCase):9 def setUp(self):10 super().setUp()11 self.data = {12 'report_counts': [13 dict(city_name='New York', num_symptoms=9666, num_deaths=123),14 dict(city_name='Los Angeles', num_symptoms=5000, num_deaths=23),15 dict(city_name='Boston', num_symptoms=800, num_deaths=250),16 dict(city_name='Detroit', num_symptoms=0, num_deaths=1),17 dict(city_name='West Yellowstone', num_symptoms=5, num_deaths=2),18 ]19 }20 template_configs_json = textwrap.dedent("""\21 [22 ["min-max-bar", {23 "question": "These {n} cities had the most reported symptoms yesterday. Which city reported the most symptoms?",24 "table": "report_counts",25 "labels": "city_name",26 "values": "num_symptoms",27 "variant": "max",28 "n": 329 }],30 ["min-max-bar", {31 "question": "These {n} cities had the most reported deaths yesterday. Which city reported the most deaths?",32 "table": "report_counts",33 "labels": "city_name",34 "values": "num_deaths",35 "variant": "max",36 "n": 437 }]38 ]""")39 self.template_configs = json.loads(template_configs_json)40 self.captcha = CaptchaGenerator(self.data, self.template_configs, response_timeout_sec=180)41 @staticmethod42 def _save_image(image_bytes, name):43 path = os.path.abspath(f'{name}.png')44 print(f'Writing image to {path}')45 with open(path, 'wb') as f:46 f.write(image_bytes)47 def test_full_flow_sanity(self):48 all_challenge_ids = set()49 all_variants = set()50 for _ in range(10):51 challenge_id, challenge, context = self.captcha.generate_challenge()52 all_challenge_ids.add(challenge_id)53 saved_context_json = context.to_json()54 loaded_context = ServerContext.from_json(saved_context_json)55 if 'symptoms' in challenge.question:56 all_variants.add('symptoms')57 self.assertEqual(set(challenge.possible_answers), {'New York', 'Los Angeles', 'Boston'})58 self.assertEqual(self.captcha.verify_response('Los Angeles', loaded_context), False)59 self.assertEqual(self.captcha.verify_response('Potato!', loaded_context), False)60 self.assertEqual(self.captcha.verify_response('New York', loaded_context), True)61 self.assertEqual(self.captcha.verify_response('New Yorx', loaded_context), True)62 else:63 all_variants.add('deaths')64 self.assertEqual(set(challenge.possible_answers), {'New York', 'Los Angeles', 'Boston', 'West Yellowstone'})65 self.assertEqual(self.captcha.verify_response('New York', loaded_context), False)66 self.assertEqual(self.captcha.verify_response('Wuhan', loaded_context), False)67 self.assertEqual(self.captcha.verify_response('Boston', loaded_context), True)68 self.assertEqual(self.captcha.verify_response('Bostn', loaded_context), True)69 self.assertEqual(len(all_challenge_ids), 10)70 self.assertEqual(all_variants, {'symptoms', 'deaths'})71 def test_full_flow_with_image(self):72 template_configs = self.template_configs[:1] # Ensure we use the symptoms challenge.73 captcha = CaptchaGenerator(self.data, template_configs, response_timeout_sec=180, rng_seed=0)74 options = RenderingOptions(figure_size=(4, 3))75 _, challenge, _ = captcha.generate_challenge(rendering_options=options)76 expected_chart = render_bar_chart([77 ('Boston', 800),78 ('New York', 9666),79 ('Los Angeles', 5000)80 ], options=options)81 if challenge.chart != expected_chart:82 # Save expected vs actual image for manual inspection / debugging.83 self._save_image(expected_chart, 'expected-chart')84 self._save_image(challenge.chart, 'actual-chart')85 self.assertEqual(challenge.chart, expected_chart)86if __name__ == '__main__':...
test_context.py
Source:test_context.py
...4from slash import ctx, context, Session5from slash.ctx import Context, ContextAttributeProxy6from slash.reporting.null_reporter import NullReporter7@pytest.mark.parametrize('on_stack', [True, False])8def test_context_dir_method_loaded_context(loaded_context, on_stack):9 output = dir(context if on_stack else loaded_context)10 assert 'test_id' in output11def test_context_dir_no_context_loaded():12 assert 'test_id' in dir(context)13def test_null_context_cant_setattr():14 with pytest.raises(AttributeError):15 context.x = 216 assert not hasattr(context, 'x')17def test_dir_object(loaded_context, queried_context):18 class Object(object):19 x = 220 y = 321 loaded_context.test_id = obj = Object()22 assert dir(queried_context.test_id) == dir(obj)23def test_call_object(loaded_context, queried_context):24 value = 'some value'25 def func():26 return value27 loaded_context.test_id = func28 assert queried_context.test_id() == value29def test_null_context():30 assert context.test_id is None31 assert context.result is None32def test_no_session_session_id(loaded_context):33 assert loaded_context.session_id is None34def test_no_session_reporter(loaded_context):35 assert isinstance(loaded_context.reporter, NullReporter)36def test_no_test_test_filename(loaded_context):37 assert loaded_context.test_filename is None38def test_session_context_result():39 with Session() as s:40 assert context.session is s41 assert context.result is s.results.global_result42def test_context_test_filename(suite, suite_test):43 suite_test.append_line('assert slash.context.test_filename == slash.context.test.__slash__.file_path')44 suite.run()45def test_test_context_result(suite):46 for test in suite:47 test.append_line('assert slash.context.result is slash.session.results[slash.context.test]')48 @slash.hooks.result_summary.register # pylint: disable=no-member49 def assert_result_back_to_normal(): # pylint: disable=unused-variable50 assert context.result is context.session.results.global_result51 assert suite.run().ok()52def test_cannot_pop_bottom():53 assert len(context._stack) == 1 # pylint: disable=protected-access54 with pytest.raises(RuntimeError):55 context.pop()56def test_push_context(loaded_context):57 test_id = loaded_context.test_id = "some_test_id"58 assert context.test_id == test_id59def test_object_proxy_getattr(contextobj, realobj):60 assert contextobj.attr is realobj.attr61 assert contextobj.__attr__ is realobj.__attr__62 assert not hasattr(contextobj, "nonexisting")63 assert not hasattr(contextobj, "__nonexisting__")64def test_object_proxy_eq(contextobj, realobj):65 assert contextobj == realobj66def test_object_proxy_ne(contextobj, realobj):67 assert not (contextobj != realobj) # pylint: disable=superfluous-parens68def test_object_proxy_str_repr(contextobj, realobj):69 assert str(contextobj) == str(realobj)70 assert repr(contextobj) == repr(realobj)71@pytest.fixture72def contextobj(loaded_context, realobj):73 setattr(loaded_context, "obj", realobj)74 return ContextAttributeProxy("obj")75@pytest.fixture76def realobj():77 class Object(object):78 __attr__ = object()79 attr = object()80 return Object()81@pytest.fixture82def loaded_context():83 returned = Context()84 context.push(returned)85 return returned86@pytest.fixture(autouse=True, scope="function")87def pop_all(request):88 @request.addfinalizer89 def cleanup(): # pylint: disable=unused-variable90 while len(context._stack) > 1: # pylint: disable=protected-access91 context.pop()92@pytest.fixture(params=['global', 'proxy'])93def queried_context(request):94 if request.param == 'global':95 return context96 elif request.param == 'proxy':...
TestTenSeal.py
Source:TestTenSeal.py
1# coding:utf-82'''3Created on 202201124@author: Yingjie Zhang5'''6import tenseal as ts7# 1. created a context for CKKS encryption8context = ts.context(ts.SCHEME_TYPE.CKKS, poly_modulus_degree=8192, coeff_mod_bit_sizes=[60, 40, 40, 60])9sk = context.secret_key()10print("sk",sk)11print()12# 2. Creating Tensors13import numpy as np14plain_tensor = np.random.randn(2, 3)15print("plain_tensor:")16print(plain_tensor)17print()18# encrypted_tensor = ts.ckks_tensor(context, plain_tensor, scale=2**40)19# print("encrypted_tensor",encrypted_tensor)20context.global_scale = 2 ** 4021encrypted_tensor = ts.ckks_tensor(context, plain_tensor)22print("encrypted_tensor:",encrypted_tensor)23print("encrypted_tensor.decrypt:",encrypted_tensor.decrypt())24print("encrypted_tensor.decrypt.tolist:")25print(encrypted_tensor.decrypt().tolist())26print()27# 3. Compute on Encrypted Tensors28encrypted_result = (encrypted_tensor + 2) * -3 - plain_tensor29expected_result = (plain_tensor + 2) * -3 - plain_tensor30print(encrypted_result.decrypt().tolist())31# [[-3.2258715329047387, -5.211344710933246, -3.277498460263318],32# [-3.320211576555451, -11.521684756232458, -5.796486356321944]]33print(expected_result)34# [[ -3.22587101 -5.21134399 -3.27749793]35# [ -3.32021105 -11.52168339 -5.79648557]]36print("inner product:")37# inner product38vec1 = np.random.randn(5)39vec2 = np.random.randn(5)40enc_vec1 = ts.ckks_tensor(context, vec1)41enc_vec2 = ts.ckks_tensor(context, vec2)42print("result:", enc_vec1.dot(enc_vec2).decrypt().tolist())43print("expected:", vec1.dot(vec2))44# result: 0.265124510512944445# expected: 0.265124488803271446print()47# 4. Batched computation48# a single ciphertext can hold up to `poly_modulus_degree / 2` values49# so let's use all the slots available50batch_size = 8192 // 2 # 409651mat1 = np.random.randn(batch_size, 2, 3)52mat2 = np.random.randn(3, 4)53# batch is by default set to False, we have to turn it on to use the packing feature of ciphertexts54enc_mat1 = ts.ckks_tensor(context, mat1, batch=True)55enc_mat2 = ts.ckks_tensor(context, mat2)56# let's just compare the first result matrix in the batch57print("result:", enc_mat1.dot(enc_mat2).decrypt().tolist()[0])58print("expected:", mat1.dot(mat2)[0])59# result: [[1.871707310741, -1.64646640599, 0.907704175882, 1.041594801418], 60# [-1.568004632635, 1.12713712214, -1.687649218268, -0.580647184131]]61# expected: [[ 1.87170707 -1.64646619 0.90770405 1.04159466]62# [-1.56800442 1.12713697 -1.68764899 -0.58064711]]63print()64# 5. More Details65# 5.1 Parallel Computation66non_parallel_context = ts.context( ts.SCHEME_TYPE.CKKS, poly_modulus_degree=8192, coeff_mod_bit_sizes=[60, 40, 40, 60], n_threads=1, )67# 5.2 Decryption68sk = context.secret_key()69context.make_context_public()70# now let's try decryption71# enc_mat1.decrypt()72# raises ValueError: the current context of the tensor doesn't hold a secret_key, please provide one as argument73# now we need to explicitly pass the secret-key74enc_mat1.decrypt(sk)75# returns <tenseal.tensors.plaintensor.PlainTensor at 0x7f391eb8dc70>76# 5.3 Serialization77ser_context = context.serialize()78print(type(ser_context))79# bytes80ser_tensor = encrypted_tensor.serialize()81print(type(ser_tensor))82# bytes83loaded_context = ts.context_from(ser_context)84print(loaded_context)85# <tenseal.enc_context.Context at 0x7f391eb8dfa0>86loaded_enc_tensor = ts.ckks_tensor_from(loaded_context, ser_tensor)87# However, there is also a way to do it the lazy way, deserializing, then linking it to a specific context88lazy_loaded_enc_tensor = ts.lazy_ckks_tensor_from(ser_tensor)89# try to operate on a tensor that in not linked to a context yet90lazy_loaded_enc_tensor + 591# raises ValueError: missing context92# You have to first link it93lazy_loaded_enc_tensor.link_context(loaded_context)94lazy_loaded_enc_tensor + 5...
test_backend.py
Source:test_backend.py
1from uuid import uuid423import spockesman45from .util import reload, BaseTestCase678class CustomContext(spockesman.Context):9 def __init__(self, *args, new_field=None, **kwargs):10 super().__init__(*args, **kwargs)11 self.new_field = new_field121314# NOTE: In this test case, we need local spockesman instances to test different backends15class BackendTest(BaseTestCase):16 @staticmethod17 def add_data(context):18 context.store('int', 1)19 context.store('bool', True)20 context.store('float', 3.3)21 context.store('str', 'string')22 context.store('list', ['string', 1, 3.3, True])23 context.store('dict', {'dict': True, '1': 3.3})2425 def simple_context_check(self, M):26 user_id = uuid4().hex27 context = M.Context(user_id)28 self.add_data(context)29 M.context.backend.database.save(context)30 loaded_context = M.context.backend.database.load(user_id)31 self.assertDictEqual(context.to_dict(), loaded_context.to_dict())32 return user_id3334 def test_backend_from_config(self):35 M = reload()36 M.setup('tests.config')37 self.simple_context_check(M)3839 def test_sqlite_backend(self):40 M = reload()41 M.context.backend.database.load_backend('sqlite_backend', {'Name': 'test_db'})42 self.simple_context_check(M)4344 def test_sqlite_backend_additional_fields(self):45 M = reload()46 M.context.backend.database.load_backend('sqlite_backend', {'Name': 'test_db'})47 user_id = uuid4().hex48 context = CustomContext(user_id, new_field='new_field_value')49 self.add_data(context)50 M.context.backend.database.save(context)51 loaded_context = M.context.backend.database.load(user_id)52 self.assertEqual(loaded_context.new_field, 'new_field_value')53 self.assertDictEqual(context.to_dict(), loaded_context.to_dict())54 self.assertEqual(type(loaded_context), CustomContext)5556 def test_sqlite_delete(self):57 M = reload()58 M.setup('tests.config')59 user_id = self.simple_context_check(M)60 M.context.backend.database.delete(user_id)61 loaded = M.context.backend.database.load(user_id)62 self.assertIsNone(loaded)63
...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!