def test_infix_to_postfix_2(): tc = TestCase() tc.assertEqual(infix_to_postfix("1 + 2 * 3"), "1 2 3 * +") tc.assertEqual(infix_to_postfix("1 / 2 + 3 * 4"), "1 2 / 3 4 * +") tc.assertEqual(infix_to_postfix("1 * 2 * 3 + 4"), "1 2 * 3 * 4 +") tc.assertEqual(infix_to_postfix("1 + 2 * 3 * 4"), "1 2 3 * 4 * +")
def test_median_1(): tc = TestCase() tc.assertEqual([3, 2.0, 3, 6.0, 9], running_medians([3, 1, 9, 25, 12]))
count1 -= matrix[y][c] if count1 == side * side: sqr += 1 return sqr class Solution: ''' 95.88% ''' def countSquares(self, matrix: List[List[int]]) -> int: res = sum(matrix[0]) for y in range(1, len(matrix)): res += matrix[y][0] for x in range(1, len(matrix[y])): if matrix[y][x] == 1: matrix[y][x] = min(matrix[y - 1][x - 1], matrix[y][x - 1], matrix[y - 1][x]) + 1 res += matrix[y][x] return res if __name__ == '__main__': t = TestCase() s = Solution() t.assertEqual(15, s.countSquares([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]])) t.assertEqual(7, s.countSquares([[1, 0, 1], [1, 1, 0], [1, 1, 0]])) print('OK!')
def __init__(self, dev, failkey): self.driver = dev self.test = Action(self.driver) self.Case = TestCase() self.failkey = failkey
def in_array(array1, array2): return sorted( filter( lambda x: max( list( map(lambda y: y.find(x), array2) ) + [-1] ) > -1, list(set(array1)) ) ) # it's imitation of JavaScript best practice a1 = ["live", "arp", "strong"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] r = ['arp', 'live', 'strong'] TestCase().assertEqual(in_array(a1, a2), r) a1 = ['arp', 'mice', 'bull'] a2 = ['lively', 'alive', 'harp', 'sharp', 'armstrong'] r = ['arp'] TestCase().assertEqual(in_array(a1, a2), r) a1 = ['duplicates', 'duplicates'] a2 = ['duplicates', 'duplicates'] r = ['duplicates'] TestCase().assertEqual(in_array(a1, a2), r)
) __all__ = [ "assert_raises", "assert_raises_regexp", "assert_array_equal", "assert_almost_equal", "assert_array_almost_equal", "assert_array_less", "assert_approx_equal", "assert_allclose", "assert_run_python_script", "SkipTest", ] _dummy = TestCase("__init__") assert_raises = _dummy.assertRaises SkipTest = unittest.case.SkipTest assert_dict_equal = _dummy.assertDictEqual assert_raises_regex = _dummy.assertRaisesRegex # assert_raises_regexp is deprecated in Python 3.4 in favor of # assert_raises_regex but lets keep the backward compat in scikit-learn with # the old name for now assert_raises_regexp = assert_raises_regex def assert_warns(warning_class, func, *args, **kw): """Test that a certain warning occurs. Parameters
from unittest import TestCase import global_functions case = TestCase() def test_get_attributes_from_class_returns_dict(): case.assertIsInstance(global_functions.get_attributes_from_class(""), dict)
def main(self): """ to run: kosmos 'j.data.schema.test(name="unique_data")' --debug #. Create schema with unique attributes and save it. #. Create another object and try to use same name for first one, should fail. #. On the second object, try to use same test var for first one, should fail. #. On the second object, try to use same new_name for first one, should success. #. On the second object, try to use same number for first one, should fail. #. Change name of the first object and try to use the first name again, should success. #. Change test var of the first object and try to use the first test var again, should success. #. Change number of the first object and try to use the first number again, should success. #. Delete the second object and create new one. #. Set the new object's attributes with the same attributes of the second object, should success. """ j.core.tools.log("Create schema with unique attributes and save it", level=20) scm = """ @url = test.schema.1 name* = "" (S) new_name = "" (S) &test = "" (S) &number = 0 (I) """ test_case = TestCase() j.servers.zdb.start_test_instance() self.admin_zdb = j.clients.zdb.client_admin_get(port=9901) self.admin_zdb.namespace_new("unique") self.zdb = j.clients.zdb.client_get(nsname="unique", port=9901) self.bcdb = j.data.bcdb.new("test", zdbclient=self.zdb) schema = j.data.schema.get(scm) self.model = self.bcdb.model_get_from_schema(schema) schema_obj = self.model.new() name = "s" + str(uuid4()).replace("-", "")[:10] new_name = "s" + str(uuid4()).replace("-", "")[:10] test = "s" + str(uuid4()).replace("-", "")[:10] number = random.randint(1, 99) schema_obj.name = name schema_obj.new_name = new_name schema_obj.test = test schema_obj.number = number schema_obj.save() j.core.tools.log( "Create another object and try to use same name for first one, should fail", level=20) schema_obj2 = self.model.new() schema_obj2.name = name with test_case.assertRaises(Exception): schema_obj2.save() schema_obj2.name = "s" + str(uuid4()).replace("-", "")[:10] j.core.tools.log( "On the second object, try to use same test var for first one, should fail", level=20) schema_obj2.test = test with test_case.assertRaises(Exception): schema_obj2.save() schema_obj2.test = "s" + str(uuid4()).replace("-", "")[:10] j.core.tools.log( "On the second object, try to use same new_name for first one, should success", level=20) schema_obj2.new_name = new_name schema_obj2.save() j.core.tools.log( "On the second object, try to use same number for first one, should fail", level=20) schema_obj2.number = number with test_case.assertRaises(Exception): schema_obj2.save() schema_obj2.number = random.randint(100, 199) j.core.tools.log( "Change name of the first object and try to use the first name again, should success", level=20) schema_obj.name = "s" + str(uuid4()).replace("-", "")[:10] schema_obj.save() schema_obj2.name = name schema_obj2.save() j.core.tools.log( "Change test var of the first object and try to use the first test var again, should success", level=20) schema_obj.test = "s" + str(uuid4()).replace("-", "")[:10] schema_obj.save() schema_obj2.test = test schema_obj2.save() j.core.tools.log( "Change number of the first object and try to use the first number again, should success", level=20) schema_obj.number = random.randint(200, 299) schema_obj.save() schema_obj2.number = number schema_obj2.save() j.core.tools.log("Delete the second object and create new one.", level=20) schema_obj2.delete() schema_obj3 = self.model.new() j.core.tools.log( "Set the new object's attributes with the same attributes of the second object, should success.", level=20) schema_obj3.name = name schema_obj3.save() schema_obj3.test = test schema_obj3.save() schema_obj3.new_name = new_name schema_obj3.save() schema_obj3.number = number schema_obj3.save() self.admin_zdb.namespace_delete("unique") j.servers.zdb.stop()
# title case # https://www.codewars.com/kata/5202ef17a402dd033c000009 from unittest import TestCase def title_case(title, minor_words=""): minor_words_lower = minor_words.lower().split(" ") result = " ".join( list( map(lambda word: word if word in minor_words_lower else word.capitalize(), title.lower().split(" ")) ) ) return result[0].upper() + result[1::] if len(result) > 0 else "" TestCase().assertEqual(title_case(''), '') TestCase().assertEqual(title_case('a clash of KINGS', 'a an the of'), 'A Clash of Kings') TestCase().assertEqual(title_case('THE WIND IN THE WILLOWS', 'The In'), 'The Wind in the Willows') TestCase().assertEqual(title_case('the quick brown fox'), 'The Quick Brown Fox')
status = 1 continue if status == 1: if (prices[i] > prices[i - 1] and i == len(prices) - 1) or prices[i - 1] < prices[i] >= prices[i + 1]: sell_point = i status = 0 profit = prices[sell_point] - prices[buy_point] + profit continue return profit def maxProfit(prices: List[int]) -> int: profit = 0 for i in range(len(prices) - 1): if prices[i] < prices[i + 1]: profit += prices[i + 1] - prices[i] return profit if __name__ == "__main__": test_case = TestCase() test_case.assertEqual(7, maxProfit([7, 1, 5, 3, 6, 4])) test_case.assertEqual(4, maxProfit([1, 2, 3, 4, 5])) test_case.assertEqual(0, maxProfit([5, 4, 3, 2, 1])) test_case.assertEqual(3, maxProfit([2, 3, 3, 5])) test_case.assertEqual(2, maxProfit([3, 3, 3, 5]))
# https://www.codewars.com/kata/5ac6932b2f317b96980000ca/ from unittest import TestCase min_value = lambda digits: int("".join(map(str, sorted(list(set(digits)))))) TestCase().assertEqual(min_value([1, 3, 1]), 13) TestCase().assertEqual(min_value([4, 7, 5, 7]), 457) TestCase().assertEqual(min_value([4, 8, 1, 4]), 148)
# https://www.codewars.com/kata/511f11d355fe575d2c000001/ from unittest import TestCase two_oldest_ages = lambda ages: sorted(ages)[-2::] TestCase().assertEqual(two_oldest_ages([1, 5, 87, 45, 8, 8]), [45, 87]) TestCase().assertEqual(two_oldest_ages([6, 5, 83, 5, 3, 18]), [18, 83]) TestCase().assertEqual(two_oldest_ages([10, 1]), [1, 10])
def test_check_delimiters_2(): tc = TestCase() tc.assertTrue(check_delimiters("([])")) tc.assertTrue(check_delimiters("[{}]")) tc.assertTrue(check_delimiters("{<()>}")) tc.assertTrue(check_delimiters("<({[]})>"))
def test_check_delimiters_1(): tc = TestCase() tc.assertTrue(check_delimiters("()")) tc.assertTrue(check_delimiters("[]")) tc.assertTrue(check_delimiters("{}")) tc.assertTrue(check_delimiters("<>"))
import pytest import json from unittest import TestCase from application.product.requests import ProductRequestConverter unittest_assertions = TestCase() @pytest.fixture def valid_request(): data = { "name": "This is name", "quantity": 12, "price": 12.50, "currency": "USD", "product_type_name": "Sport", "product_type_id": "this is and id", "images": [{ "name": "Image", "url": "This is a valid image url" }] } return json.dumps(data).encode("utf-8") @pytest.fixture def converter(): return ProductRequestConverter() def test_convert_request_data_bytes_to_product_dto(converter, valid_request):
# Count characters in your string # https://www.codewars.com/kata/52efefcbcdf57161d4000091/ from unittest import TestCase def count(string): result = {} for char in list(string): if char in result: result[char] = result[char] + 1 else: result[char] = 1 return result TestCase().assertEqual(count('aba'), {'a': 2, 'b': 1}) TestCase().assertEqual(count(''), {})
"""Supports iteration (via `iter(self)`)""" #code for i in range(0, len(self.data)): yield self.data[i] #raise NotImplementedError() # In[5]: # (6 points) test subscript-based access from unittest import TestCase import random tc = TestCase() lst = ArrayList() data = [1, 2, 3, 4] lst.data = ConstrainedList(data) for i in range(len(data)): tc.assertEqual(lst[i], data[i]) with tc.assertRaises(IndexError): x = lst[100] with tc.assertRaises(IndexError): lst[100] = 0 with tc.assertRaises(IndexError): del lst[100]
# https://www.codewars.com/kata/count-the-monkeys/ from unittest import TestCase monkey_count = lambda n: [x for x in range(1, n + 1)] TestCase().assertEqual(monkey_count(5), [1, 2, 3, 4, 5]) TestCase().assertEqual(monkey_count(3), [1, 2, 3]) TestCase().assertEqual(monkey_count(9), [1, 2, 3, 4, 5, 6, 7, 8, 9]) TestCase().assertEqual(monkey_count(10), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) TestCase().assertEqual( monkey_count(20), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
def test_case(): return TestCase()
# highest-scoring-word # https://www.codewars.com/kata/57eb8fcdf670e99d9b000272 from unittest import TestCase from functools import reduce def high(x): sorted_value = sorted( [(word, reduce(lambda a, b: a + ord(b) - 96, list(word), 0)) for word in x.split(" ")], key=lambda v: v[1]) return list(filter(lambda v: v[1] == sorted_value[-1][1], sorted_value))[0][0] TestCase().assertEqual(high('man i need a taxi up to ubud'), 'taxi') TestCase().assertEqual(high('what time are we climbing up the volcano'), 'volcano') TestCase().assertEqual(high('take me to semynak'), 'semynak')
def test_responses(uuid, get_folder_fixture, postman_json): folder = get_folder_fixture(postman_json["item"], "Request Methods") samplerequestitem = folder["item"][0] assert isinstance(samplerequestitem, dict) request_item = RequestItemParser(samplerequestitem) response_spec = Operation(request_item).responses() TestCase().assertEqual( { 200: { "content": { "application/json": { "schema": { "type": "object", "properties": { "args": { "type": "object", "properties": { "foo1": {"type": "string"}, "foo2": {"type": "string"}, }, "required": ["foo1", "foo2"], }, "headers": { "type": "object", "properties": { "x-forwarded-proto": {"type": "string"}, "host": {"type": "string"}, "accept": {"type": "string"}, "accept-encoding": {"type": "string"}, "cache-control": {"type": "string"}, "postman-token": {"type": "string"}, "user-agent": {"type": "string"}, "x-forwarded-port": {"type": "string"}, }, "required": [ "x-forwarded-proto", "host", "accept", "accept-encoding", "cache-control", "postman-token", "user-agent", "x-forwarded-port", ], }, "url": {"type": "string"}, }, "required": ["args", "headers", "url"], "title": "GET Request Woops", }, "examples": { "GetRequestWoops": { "value": { "args": { "foo1": "bar1", "foo2": "bar2", }, "headers": { "x-forwarded-proto": "https", "host": "postman-echo.com", "accept": "*/*", "accept-encoding": "gzip, deflate", "cache-control": "no-cache", "postman-token": "5c27cd7d-6b16-4e5a-a0ef-191c9a3a275f", "user-agent": "PostmanRuntime/7.6.1", "x-forwarded-port": "443", }, "url": "https://postman-echo.com/get?foo1=bar1&foo2=bar2", }, "x-response-id": "a", } }, } }, "description": "GET Request Woops", } }, response_spec, )
def test_custor_based_access(): say_test("test_custor_based_access") tc = TestCase() ## insert a bunch of values at different cursor positions lst1 = [] lst2 = LinkedList() for _ in range(100): val = random.randrange(1000) lst1.append(val) lst2.append(val) for _ in range(10): pos = random.randrange(len(lst1)) vals = [random.randrange(1000) for _ in range(10)] lst1[pos+1:pos+1] = vals lst2.cursor_set(pos) for x in vals: lst2.cursor_insert(x) assert len(lst1) == len(lst2) for i in range(len(lst1)): assert lst1[i] == lst2[i] ## move the cursor around and check that values are correct lst1 = [] lst2 = LinkedList() for _ in range(100): val = random.randrange(1000) lst1.append(val) lst2.append(val) idx = 0 lst2.cursor_set(0) for _ in range(100): offset = random.randrange(-200, 200) idx = (idx + offset) % 100 lst2.cursor_move(offset) assert lst1[idx] == lst2.cursor_get() ## move the cursor around and delete values at the cursor lst1 = [] lst2 = LinkedList() for _ in range(500): val = random.randrange(1000) lst1.append(val) lst2.append(val) idx = 0 lst2.cursor_set(0) for _ in range(100): offset = random.randrange(-200, 200) idx = (idx + offset) % len(lst1) lst2.cursor_move(offset) del lst1[idx] lst2.cursor_delete() assert len(lst1) == len(lst2) for i in range(len(lst1)): assert lst1[i] == lst2[i]
# -*- coding: utf-8 -*- # pylint: disable=missing-docstring,no-self-use,too-few-public-methods,invalid-name """ Test cases for documents in ddionrails.data app """ from unittest import TestCase import pytest from django.forms.models import model_to_dict from ddionrails.data.documents import VariableDocument pytestmark = [pytest.mark.search] TEST_CASE = TestCase() @pytest.mark.usefixtures("variables_index") def test_variable_search_document_fields(variable): search = VariableDocument.search().query("match_all") expected = 1 TEST_CASE.assertEqual(expected, search.count()) response = search.execute() document = response.hits[0] # test meta TEST_CASE.assertEqual(str(variable.id), document.meta.id) TEST_CASE.assertEqual("testing_variables", document.meta.index) # generate expected dictionary with attributes from model instance
def __init__(self, parent): self.parent = parent if parent is not None else TestCase()
# https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d from unittest import TestCase solution = lambda str, ending: str.endswith(ending) TestCase().assertEqual(solution('abcde', 'cde'), True) TestCase().assertEqual(solution('abcde', 'abc'), False) TestCase().assertEqual(solution('abcde', ''), True)
def fake_inout_setup(inout_controller): TestCase().assertEqual( setup_controller(inout_controller, SetupPolicyRequest(requests=[], epoch=global_epoch)), SetupFlowsResult.SUCCESS)
def test_median_2(): tc = TestCase() vals = [random.randrange(10000) for _ in range(1000)] tc.assertEqual(running_medians_naive(vals), running_medians(vals))
import sklearn from sklearn.base import (BaseEstimator, ClassifierMixin, ClusterMixin, RegressorMixin, TransformerMixin) from sklearn.utils import deprecated, IS_PYPY, _IS_32BIT __all__ = [ "assert_equal", "assert_not_equal", "assert_raises", "assert_raises_regexp", "assert_almost_equal", "assert_array_equal", "assert_array_almost_equal", "assert_array_less", "assert_less", "assert_less_equal", "assert_greater", "assert_greater_equal", "assert_approx_equal", "assert_allclose", "assert_run_python_script", "SkipTest", "all_estimators" ] _dummy = TestCase('__init__') deprecation_message = ( 'This helper is deprecated in version 0.22 and will be removed in version ' '0.24. Please use "assert" instead') assert_equal = deprecated(deprecation_message)(_dummy.assertEqual) assert_not_equal = deprecated(deprecation_message)(_dummy.assertNotEqual) assert_raises = _dummy.assertRaises SkipTest = unittest.case.SkipTest assert_dict_equal = _dummy.assertDictEqual assert_in = deprecated(deprecation_message)(_dummy.assertIn) assert_not_in = deprecated(deprecation_message)(_dummy.assertNotIn) assert_less = deprecated(deprecation_message)(_dummy.assertLess) assert_greater = deprecated(deprecation_message)(_dummy.assertGreater) assert_less_equal = deprecated(deprecation_message)(_dummy.assertLessEqual) assert_greater_equal = deprecated(deprecation_message)( _dummy.assertGreaterEqual)
# -*- coding: utf-8 -*- import os.path as path from unittest import TestCase from server_support import server, H from amara.thirdparty import json DIR_FIXTURES = path.join(path.abspath(path.split(__file__)[0]), 'fixtures') #http://stackoverflow.com/questions/18084476/is-there-a-way-to-use-python-unit-test-assertions-outside-of-a-testcase TC = TestCase('__init__') def _get_server_response(body): url = server() + "dpla_mapper?mapper_type=ucldc_nuxeo" return H.request(url, "POST", body=body) def test_ucldc_nuxeo_mapping(): fixture = path.join(DIR_FIXTURES, 'ucldc-nuxeo.json') with open(fixture) as f: INPUT = f.read() resp, content = _get_server_response(INPUT) assert resp.status == 200 obj = json.loads(content) TC.assertIn('isShownAt', obj) TC.assertIn('isShownBy', obj) TC.assertEqual(obj['isShownBy'], "http://example.edu/this/is/image/URL") TC.assertEqual( obj['isShownAt'], "https://calisphere.org/item/40677ed1-f7c2-476f-886d-bf79c3fec8c4")
def test_check_delimiters_6(): tc = TestCase() tc.assertFalse(check_delimiters("[ ( ] )")) tc.assertFalse(check_delimiters("((((((( ))))))")) tc.assertFalse(check_delimiters("< < > > >")) tc.assertFalse(check_delimiters("( [] < {} )"))