def run(self): # try reading various ranges (these are (start, end) absolute ranges, not offset/length) ranges = [ (0, 16384), (1, 200), (0, 4096), (0, 8192), (0, 1000), (0, 6000), (100, 4000), (5000, 10000), (4096, 10000), (5000, 8192), (4096, 16834), (5000, 16384), (4096, 16000), (5000, 16000) ] self.exitcode = 0 for (start, end) in ranges: if self.errors: break # only clear reader's cache testlib.clear_cache( self.config_dir, volume_id=self.volume_id, gateway_id=self.read_gateway_id ) for i in xrange(0, 2): if self.errors: break exitcode, out = testlib.run( READ_PATH, '-d2', '-f', '-c', os.path.join(self.config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', self.volume_name, '-g', self.read_gateway_name, self.output_path, start, end - start, valgrind=True ) out_name = "uncached" if i > 0: out_name = "cached" testlib.save_output( self.output_dir, 'syndicate-read-thread-%s-%s-%s-%s' % (self.get_ident(), start, end, out_name), out ) if exitcode != 0: self.exitcode = exitcode self.errormsg = "syndicate-read exit code %s on %s-%s-%s" % (exitcode, start, end, out_name) break # correctness if expected_data[start:end] not in out: self.exitcode = -1 self.errormsg = "Thread %s missing data for %s-%s-%s" % (self.get_ident(), start, end, out_name) break if self.exitcode != 0: break return
# Note: # 1 <= stones.length <= 30 # 1 <= stones[i] <= 1000 from typing import List from bisect import insort import testlib class Solution: def lastStoneWeight(self, stones: List[int]) -> int: ss = sorted(stones) while True: if len(ss) == 0: return 0 if len(ss) == 1: return ss[0] a = ss.pop() b = ss.pop() if a == b: continue insort(ss, abs(a - b)) if __name__ == "__main__": testdata = [([2, 7, 4, 1, 8, 1], 1)] testlib.run( lambda t, tc: t.assertEqual(Solution().lastStoneWeight(tc[0]), tc[1], tc), testdata, )
volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN) gateway_client_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN) testlib.update_gateway(config_dir, gateway_client_name, "port=31112") random_part = hex(random.randint(0, 2**32 - 1))[2:] exitcode, out = testlib.run(TOUCH_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, path) testlib.save_output(output_dir, "syndicate-touch", out) if exitcode != 0: raise Exception("Failed to touch %s" % path) # do setxattr a few times # 1 attr exitcode, out_1attr = testlib.run(SETXATTR_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'),
# Output: [1,2,4,8] import testlib from typing import List class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: if len(nums) < 2: return nums todo = sorted(nums) divisibles = [[n] for n in todo] max_len_and_idx = (1, 0) for i, n in enumerate(todo): for check_idx in range(0, i): if n % todo[check_idx] == 0: if len(divisibles[check_idx]) + 1 > len(divisibles[i]): divisibles[i] = divisibles[check_idx] + [n] if len(divisibles[i]) > max_len_and_idx[0]: max_len_and_idx = (len(divisibles[i]), i) return divisibles[max_len_and_idx[1]] if __name__ == "__main__": testdata = [([1, 2, 3], [[1, 2], [1, 3]]), ([1, 2, 4, 8], [[1, 2, 4, 8]])] testlib.run( lambda t, tc: t.assertIn(Solution().largestDivisibleSubset(tc[0]), tc[ 1], tc), testdata, )
import testlib class Solution: def backspaceCompare(self, S: str, T: str) -> bool: def evalString(s: str) -> str: out = [] for c in s: if c == "#": if len(out) > 0: out.pop() else: out.append(c) return "".join(out) return evalString(S) == evalString(T) if __name__ == "__main__": testdata = [ ("ab#c", "ad#c", True), ("ab##", "c#d#", True), ("a##c", "#a#c", True), ("a#c", "b", False), ] testlib.run( lambda t, tc: t.assertEqual(Solution().backspaceCompare(tc[0], tc[1]), tc[2], tc), testdata, )
gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) getxattr_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", port=31113, email=testconf.SYNDICATE_ADMIN ) rg_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "RG", caps="NONE", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway( config_dir, rg_gateway_name, "port=31112", "driver=%s" % RG_DRIVER ) # start the RG rg_proc, rg_out_path = testlib.start_gateway( config_dir, RG_PATH, testconf.SYNDICATE_ADMIN, volume_name, rg_gateway_name ) if not testlib.gateway_ping( 31112, 15 ): stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll())) # put the file... exitcode, out = testlib.run( PUT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, random_file_path, path ) testlib.save_output( output_dir, "syndicate-put", out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("Failed to touch %s" % path) # finish populating expected built-in xattrs exitcode, out = testlib.run( STAT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, "syndicate.conf"), "-u", testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', getxattr_gateway_name, path ) testlib.save_output( output_dir, "syndicate-stat", out ) if exitcode != 0:
# start AG AG_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "AG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway( config_dir, AG_gateway_name, "port=31112", "driver=%s" % AG_DRIVER ) ag_proc, ag_out_path = testlib.start_gateway( config_dir, AG_PATH, testconf.SYNDICATE_ADMIN, volume_name, AG_gateway_name, valgrind=True ) time.sleep(20) if ag_proc.poll() is not None: ag_exitcode, ag_out = testlib.stop_gateway( ag_proc, ag_out_path ) testlib.save_output(output_dir, "syndicate-ag", ag_out) raise Exception("%s exited %s" % (AG_PATH, ag_proc.poll())) # should cause the AG to get updated that there's a new gateway cat_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) exitcode, out = testlib.run( CAT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', cat_gateway_name, *output_paths, valgrind=True ) testlib.save_output(output_dir, "syndicate-cat", out ) if exitcode != 0: ag_exitcode, ag_out = testlib.stop_gateway( ag_proc, ag_out_path ) testlib.save_output(output_dir, "syndicate-ag", ag_out) raise Exception("%s exited %s" % (CAT_PATH, exitcode)) # should get all data for i in xrange(0, len(expected_datas)): ed = expected_datas[i] if ed not in out: ag_exitcode, ag_out = testlib.stop_gateway( ag_proc, ag_out_path ) testlib.save_output(output_dir, "syndicate-ag", ag_out) raise Exception("Missing expected data for %s" % output_paths[i])
gateway_name = testlib.add_test_gateway(config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN) gateway_client_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway(config_dir, gateway_client_name, "port=31112") random_part = hex(random.randint(0, 2 ** 32 - 1))[2:] exitcode, out = testlib.run( TOUCH_PATH, "-d2", "-f", "-c", os.path.join(config_dir, "syndicate.conf"), "-u", testconf.SYNDICATE_ADMIN, "-v", volume_name, "-g", gateway_name, path, ) testlib.save_output(output_dir, "syndicate-touch", out) if exitcode != 0: raise Exception("Failed to touch %s" % path) # do setxattr a few times # 1 attr exitcode, out_1attr = testlib.run(
def step_impl(context, rpm): rpm = context.download_rpm(rpm) shutil.move(rpm, context.local_repo) run(["createrepo_c", context.local_repo])
def step_impl(context): context.local_repo = tempfile.mkdtemp(prefix="mock-tests-local-repo-") run(["createrepo_c", context.local_repo])
# "bbAa" # Explanation: # "bbaA" is also a valid answer, but "Aabb" is incorrect. # Note that 'A' and 'a' are treated as two different characters. import testlib from typing import Dict class Solution: def frequencySort(self, s: str) -> str: freqs: Dict[str, int] = {} for c in s: freqs[c] = freqs.get(c, 0) + 1 out = [] for k in sorted(freqs, key=lambda x: -freqs[x]): out.append(k * freqs[k]) return "".join(out) if __name__ == "__main__": testdata = [ ("tree", ["eert", "eetr"]), ("cccaaa", ["cccaaa", "aaaccc"]), ("Aabb", ["bbAa", "bbaA"]), ] testlib.run( lambda t, tc: t.assertIn(Solution().frequencySort(tc[0]), tc[1], tc), testdata, )
("put", (4, 4), None), ("get", (1, ), -1), ("get", (3, ), 3), ("get", (4, ), 4), ], [ ("new", (2, ), None), ("put", (2, 1), None), ("put", (1, 1), None), ("put", (2, 3), None), ("put", (4, 1), None), ("get", (1, ), -1), ("get", (2, ), 3), ], ] def execute(t: testlib.unittest.TestCase, statements: List[Tuple[str, Tuple, Optional[int]]]): obj = None for (instruction, args, expected) in statements: if instruction == "new": obj = LRUCache(args[0]) elif instruction == "put": obj.put(args[0], args[1]) elif instruction == "get": res = obj.get(args[0]) if expected is not None: t.assertEqual(res, expected) testlib.run(lambda t, tc: execute(t, tc), testdata)
# Output: 1 # # Note: # You can assume that # - 0 <= amount <= 5000 # - 1 <= coin <= 5000 # - the number of coins is less than 500 # - the answer is guaranteed to fit into signed 32-bit integer import testlib from typing import List class Solution: def change(self, amount: int, coins: List[int]) -> int: answers_by_amount = [0 for _ in range(amount + 1)] answers_by_amount[0] = 1 for coin in sorted(coins): for amt in range(coin, amount + 1): answers_by_amount[amt] += answers_by_amount[amt - coin] return answers_by_amount[amount] if __name__ == "__main__": testdata = [(5, [1, 2, 5], 4), (3, [2], 0), (10, [10], 1)] testlib.run( lambda t, tc: t.assertEqual(Solution().change(tc[0], tc[1]), tc[2], tc ), testdata, )
# return 2. # Note: You may assume the string contain only lowercase letters. import testlib from collections import OrderedDict class Solution: def firstUniqChar(self, s: str) -> int: seen = set() candidates = OrderedDict() for (i, c) in enumerate(s): if c not in seen: seen.add(c) candidates[c] = i elif c in candidates: del candidates[c] if len(candidates) > 0: (c, i) = candidates.popitem(False) return i else: return -1 if __name__ == "__main__": testdata = [("leetcode", 0), ("loveleetcode", 2), ("aabbcc", -1)] testlib.run( lambda t, tc: t.assertEqual(Solution().firstUniqChar(tc[0]), tc[1], tc), testdata, )
volume_name = testlib.add_test_volume( config_dir ) RG_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "RG", caps="NONE", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway( config_dir, RG_gateway_name, "port=31112", "driver=%s" % RG_DRIVER ) rg_proc, rg_out_path = testlib.start_gateway( config_dir, RG_PATH, testconf.SYNDICATE_ADMIN, volume_name, RG_gateway_name ) if not testlib.gateway_ping( 31112, 15 ): raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll())) # should cause the RG to get updated that there's a new gateway gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) cat_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) random_part = hex(random.randint(0, 2**32-1))[2:] output_path = "/put-%s" % random_part exitcode, out = testlib.run( PUT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, local_path, output_path ) testlib.save_output( output_dir, "syndicate-put", out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (PUT_PATH, exitcode)) exitcode, out = testlib.run( STAT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', cat_gateway_name, output_path ) testlib.save_output( output_dir, 'syndicate-stat', out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (STAT_PATH, exitcode))
# look up RG rg_gateway_info = testlib.read_gateway( config_dir, RG_gateway_name ) rg_gateway_id = rg_gateway_info['g_id'] volume_info = testlib.read_volume( config_dir, volume_name ) volume_id = volume_info['volume_id'] random_part = hex(random.randint(0, 2**32-1))[2:] output_paths = [] for i in xrange(0, NUM_FILES): output_path = "/put-%s-%s" % (random_part, i) output_paths.append(output_path) exitcode, out = testlib.run( PUT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, local_path, output_path, valgrind=True ) testlib.save_output( output_dir, "syndicate-put-%s" % i, out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (PUT_PATH, exitcode)) # make target directory exitcode, out = testlib.run( MKDIR_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, "/newdir", valgrind=True ) testlib.save_output( output_dir, "syndicate-mkdir", out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (PUT_PATH, exitcode)) # do several renames
def step_impl(context, options): options = options.split() context.last_cmd = run(['mock'] + options)
if not testlib.gateway_ping( 31112, 15 ): raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll())) # should cause the RG to get updated that there's a new gateway gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) read_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) read_gateway_info = testlib.read_gateway( config_dir, read_gateway_name ) read_gateway_id = read_gateway_info['g_id'] volume_info = testlib.read_volume( config_dir, volume_name ) volume_id = volume_info['volume_id'] random_part = hex(random.randint(0, 2**32-1))[2:] output_path = "/put-%s" % random_part exitcode, out = testlib.run( PUT_PATH, '-d3', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, local_path, output_path ) testlib.save_output( output_dir, "syndicate-put", out ) if exitcode != 0: raise Exception("%s exited %s" % (PUT_PATH, exitcode)) # try reading and writing various ranges (these are (start, end) absolute ranges, not offset/length) ranges = [ (5000, 16000), (0, 1), # 1 block, tail unaligned (1, 200), # 1 block, unaligned head and tail (0, 4096), # 4 block, aligned (0, 8192), # 8 blocks, aligned (0, 1000), # 1 block, tail unaligned (0, 6000),
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: solutions = [[0 for _ in B] for _ in A] def get(r: int, c: int) -> int: if r < 0 or c < 0: return 0 return solutions[r][c] for (r, a) in enumerate(A): for (c, b) in enumerate(B): solutions[r][c] = max( get(r - 1, c), get(r, c - 1), get(r - 1, c - 1) + int(a == b) ) return solutions[-1][-1] if __name__ == "__main__": testdata = [ ([1, 4, 2], [1, 2, 4], 2), ([2, 5, 1, 2, 5], [10, 5, 2, 1, 5, 2], 3), ([1, 3, 7, 1, 7, 5], [1, 9, 2, 5, 1], 2), ] testlib.run( lambda t, tc: t.assertEqual( Solution().maxUncrossedLines(tc[0], tc[1]), tc[2], tc ), testdata, )
if __name__ == "__main__": random_part = hex(random.randint(0, 2**32-1))[2:] path = '/setxattr-%s' % random_part attr_name_base = 'foo-%s' % random_part attr_value_base = 'bar-%s' % random_part config_dir, output_dir = testlib.test_setup() volume_name = testlib.add_test_volume( config_dir ) gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) random_part = hex(random.randint(0, 2**32-1))[2:] exitcode, out = testlib.run( TOUCH_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, path ) testlib.save_output( output_dir, "syndicate-touch", out ) if exitcode != 0: raise Exception("Failed to touch %s" % path) # do setxattr a few times # 1 attr exitcode, out_1attr = testlib.run( SETXATTR_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, path, attr_name_base + "-1attr", attr_value_base + "-1attr", valgrind=True ) testlib.save_output( output_dir, "syndicate-setxattr-1attr", out_1attr ) if exitcode != 0:
min_to_end[r][-1] = inf for c in range(len(dungeon[0])): min_to_end[-1][c] = inf min_to_end[len(dungeon) - 1][-1] = min_health min_to_end[-1][len(dungeon[0]) - 1] = min_health for r in range(len(dungeon) - 1, -1, -1): for c in range(len(dungeon[0]) - 1, -1, -1): min_to_end[r][c] = max( min(min_to_end[r + 1][c], min_to_end[r][c + 1]) - dungeon[r][c], min_health, ) return min_to_end[0][0] if __name__ == "__main__": testdata = [ ([[-2, -3, 3], [-5, -10, 1], [10, 30, -5]], 7), ([[0]], 1), ([[100]], 1), ([[-200]], 201), ([[0, 0]], 1), ([[0, -2, 10, -5]], 3), ([[1, -3, 3], [0, -2, 0], [-3, -3, -3]], 3), ] testlib.run( lambda t, tc: t.assertEqual(Solution().calculateMinimumHP(tc[0]), tc[ 1], tc), testdata, )
if end - start == 0: raise ValueError("empty chunk at position {}".format(start)) if end - start > 4: raise ValueError( "chunk longer than 4 characters at position {}: {}".format( start, ip[start:end])) for i in range(start, end): char = ip[i] if not (char.isdecimal() or char.lower() in "abcdef"): raise ValueError("invalid hex digit at position {}: {}".format( i, char)) return end if __name__ == "__main__": testdata = [ ("172.16.254.1", "IPv4"), ("172.16.254.0", "IPv4"), ("172.16.254.03", "Neither"), ("172.16.254", "Neither"), ("256.256.256.256", "Neither"), ("2001:0db8:85a3:0:0:8A2E:0370:7334", "IPv6"), ("02001:0db8:85a3:0:0:8A2E:0370:7334", "Neither"), ("2001:0db8:85a3::8A2E:0370:7334", "Neither"), ] testlib.run( lambda t, tc: t.assertEqual(Solution().validIPAddress(tc[0]), tc[1], tc ), testdata, )
# Explanation: 2^0 = 1 # # Example 2: # Input: 16 # Output: true # Explanation: 2^4 = 16 # # Example 3: # Input: 218 # Output: false import testlib class Solution: def isPowerOfTwo(self, n: int) -> bool: if n < 1: return False while n: if n > 1 and n & 1: return False n >>= 1 return True if __name__ == "__main__": testdata = [(1, True), (16, True), (218, False), (0, False), (-16, False)] testlib.run( lambda t, tc: t.assertEqual(Solution().isPowerOfTwo(tc[0]), tc[1], tc), testdata)
path = '/setxattr-%s' % random_part attr_name_base = 'foo-%s' % random_part attr_value_base = 'bar-%s' % random_part expected_listxattr_output = "" config_dir, output_dir = testlib.test_setup() volume_name = testlib.add_test_volume( config_dir ) gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) gateway_client_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway( config_dir, gateway_client_name, "port=31112" ) random_part = hex(random.randint(0, 2**32-1))[2:] exitcode, out = testlib.run( TOUCH_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, path ) testlib.save_output( output_dir, "syndicate-touch", out ) if exitcode != 0: raise Exception("Failed to touch %s" % path) # do setxattr a few times # 1 attr exitcode, out_1attr = testlib.run( SETXATTR_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, path, attr_name_base + "-1attr", attr_value_base + "-1attr", valgrind=True ) expected_listxattr_output += attr_name_base + "-1attr" + '\n'
email=testconf.SYNDICATE_ADMIN) testlib.update_gateway(config_dir, rg_gateway_name, "port=31112", "driver=%s" % RG_DRIVER) # start the RG rg_proc, rg_out_path = testlib.start_gateway(config_dir, RG_PATH, testconf.SYNDICATE_ADMIN, volume_name, rg_gateway_name) if not testlib.gateway_ping(31112, 15): stop_and_save(output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll())) # put the file... exitcode, out = testlib.run(PUT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, random_file_path, path) testlib.save_output(output_dir, "syndicate-put", out) if exitcode != 0: stop_and_save(output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("Failed to touch %s" % path) # finish populating expected built-in xattrs exitcode, out = testlib.run(STAT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, "syndicate.conf"), "-u", testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', getxattr_gateway_name, path)
if not head or head.next is None: return head odd = head even = head.next even_head = even while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head return head if __name__ == "__main__": testdata = [ ([1], [1]), ([1, 2], [1, 2]), ([1, 2, 3], [1, 3, 2]), ([1, 2, 3, 4, 5], [1, 3, 5, 2, 4]), ([2, 1, 3, 5, 6, 4, 7], [2, 3, 6, 7, 1, 5, 4]), ] testlib.run( lambda t, tc: t.assertEqual( repr(Solution().oddEvenList(ListNode.fromList(tc[0]))), repr(ListNode.fromList(tc[1])), tc, ), testdata, )
bits = 64 counts = [0] * bits for num in nums: for bit in range(bits): if num & (1 << bit): counts[bit] += 1 out = 0 for bit, count in enumerate(counts): if count % 3 > 0: out |= 1 << bit return out if __name__ == "__main__": testdata = [ ([-2, -2, 1, 1, -3, 1, -3, -3, -4, -2], -4), ([2, 2, 3, 2], 3), ([0, 1, 0, 1, 0, 1, 99], 99), ([-2, -2, -2, 1], 1), ( [ -19, -46, -19, -46, -9, -9, -19, 17, 17, 17, -13, -13, -9, -13, -46, -28 ], -28, ), ] testlib.run( lambda t, tc: t.assertEqual(Solution().singleNumber(tc[0]), tc[1], tc), testdata)
@staticmethod def fromList(input: List) -> "ListNode": nodes = [ListNode(el) for el in input] for i in range(len(nodes) - 1): nodes[i].next = nodes[i + 1] return nodes[0] class Solution: def middleNode(self, head: ListNode) -> ListNode: slow = head fast = head.next while fast is not None: slow = slow.next fast = fast.next if fast is None: break fast = fast.next return slow if __name__ == "__main__": testdata = [([1, 2, 3, 4, 5], 3), ([1, 2, 3, 4, 5, 6], 4)] testlib.run( lambda t, tc: t.assertEqual( Solution().middleNode(ListNode.fromList(tc[0])).val, tc[1], tc ), testdata, )
def getPermutation(self, n: int, k: int) -> str: # Use factorial permutation indices as described here: # https://www.keithschwarz.com/interesting/code/?dir=factoradic-permutation # or here: # https://py.checkio.org/mission/reversed-permutation-index/publications/sjosef23/python-3/some-more-magic-and-factorials/share/473022125e05dd4f79c8e51f4a67b4fe/ idx = k - 1 facs = [1] * n for i in range(3, n + 1): facs[n - i] = facs[n - i + 1] * (i - 1) indices_in_remaining = [] for fac in facs: digit = idx // fac indices_in_remaining.append(digit) idx -= digit * fac digits = list(range(1, n + 1)) out = "" for i in indices_in_remaining: out += str(digits.pop(i)) return out if __name__ == "__main__": testdata = [(4, 9, "2314"), (3, 3, "213")] testlib.run( lambda t, tc: t.assertEqual(Solution().getPermutation(tc[0], tc[1]), tc[2], tc), testdata, )
if sys.version_info[0] == 2: import pthreading pthreading.monkey_patch() from vdsm.common import zombiereaper zombiereaper.registerSignalHandler() import testlib def findRemove(listR, value): """used to test if a value exist, if it is, return true and remove it.""" try: listR.remove(value) return True except ValueError: return False if __name__ == '__main__': if "--help" in sys.argv: print("testrunner options:\n" "--local-modules use vdsm modules from source tree, " "instead of installed ones.\n") if findRemove(sys.argv, "--local-modules"): from vdsm import constants from vdsm.common import constants as common_constants common_constants.P_VDSM = constants.P_VDSM = "../vdsm/" testlib.run()
# list. # - Do not return anything from your function. import testlib from listnode import ListNode from typing import List, Tuple class Solution: def deleteNode(self, node: ListNode): node.val = node.next.val node.next = node.next.next def run_test_case(t: testlib.unittest.TestCase, tc: Tuple[List[int], int, List[int]]): head = ListNode.fromList(tc[0]) el_to_remove = head for _ in range(tc[1]): el_to_remove = el_to_remove.next Solution().deleteNode(el_to_remove) t.assertEqual(repr(head), repr(ListNode.fromList(tc[2]))) if __name__ == "__main__": testdata = [ ([4, 5, 1, 9], 1, [4, 1, 9]), ([4, 5, 1, 9], 2, [4, 5, 9]), ([2, 0, 1, 3], 0, [0, 1, 3]), ] testlib.run(run_test_case, testdata)
# look up reader gateway cat_gateway_info = testlib.read_gateway( config_dir, cat_gateway_name ) cat_gateway_id = cat_gateway_info['g_id'] # look up RG rg_gateway_info = testlib.read_gateway( config_dir, RG_gateway_name ) rg_gateway_id = rg_gateway_info['g_id'] volume_info = testlib.read_volume( config_dir, volume_name ) volume_id = volume_info['volume_id'] random_part = hex(random.randint(0, 2**32-1))[2:] output_paths = [] # make target directory exitcode, out = testlib.run( MKDIR_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, "/newdir", valgrind=True ) testlib.save_output( output_dir, "syndicate-mkdir", out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (PUT_PATH, exitcode)) # generate the commands to feed into the REPL repl_cmd = "" for i in xrange(0, NUM_FILES): output_path = "/put-%s-%s" % (random_part, i) output_paths.append(output_path) repl_cmd += "create %s 0644\n" % output_path repl_cmd += "write 0 0 %s %s\n" % (len(write_data), write_data)
# Explanation: You will always arrive at index 3 no matter what. Its maximum jump length # is 0, which makes it impossible to reach the last index. import testlib from typing import List class Solution: def canJump(self, nums: List[int]) -> bool: target = len(nums) - 1 max_reachable = 0 for (i, n) in enumerate(nums): if max_reachable >= target: return True if max_reachable < i: break max_reachable = max(max_reachable, i + n) return max_reachable >= target if __name__ == "__main__": testdata = [ ([2, 3, 1, 1, 4], True), ([3, 2, 1, 0, 4], False), ([2, 5, 0, 0], True), ([0], True), ] testlib.run( lambda t, tc: t.assertEqual(Solution().canJump(tc[0]), tc[1], tc), testdata)
rg_proc, rg_out_path = testlib.start_gateway( config_dir, RG_PATH, testconf.SYNDICATE_ADMIN, volume_name, RG_gateway_name ) if not testlib.gateway_ping( 31112, 15 ): raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll())) # should cause the RG to get updated that there's a new gateway gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) # touch $NUM_FILES files random_part = hex(random.randint(0, 2**32-1))[2:] expected_paths = [] for i in xrange(0, NUM_FILES): output_path = "/touch-%s-%s" % (random_part, i) expected_paths.append(output_path) exitcode, out = testlib.run( TOUCH_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, output_path ) testlib.save_output( output_dir, "syndicate-touch-%s" % i, out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (TOUCH_PATH, exitcode)) # list them exitcode, out = testlib.run( LS_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, '/' ) testlib.save_output( output_dir, "syndicate-ls", out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (LS_PATH, exitcode)) # verify that they're all there for path in expected_paths: if path.strip("/") not in out:
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: min_idx = 0 max_idx = len(nums) while min_idx < max_idx: test_idx = (min_idx + max_idx) // 2 if nums[test_idx] < target: min_idx = test_idx + 1 elif nums[test_idx] == target: return test_idx else: max_idx = test_idx return min_idx if __name__ == "__main__": testdata = [ ([1, 3, 5, 6], 5, 2), ([1, 3, 5, 6], 2, 1), ([1, 3, 5, 6], 7, 4), ([1, 3, 5, 6], 0, 0), ([1, 3], 2, 1), ] testlib.run( lambda t, tc: t.assertEqual(Solution().searchInsert(tc[0], tc[1]), tc[ 2], tc), testdata, )
volume_name = testlib.add_test_volume( config_dir, blocksize=block_size ) RG_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "RG", caps="NONE", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway( config_dir, RG_gateway_name, "port=31112", "driver=%s" % RG_DRIVER ) rg_proc, rg_out_path = testlib.start_gateway( config_dir, RG_PATH, testconf.SYNDICATE_ADMIN, volume_name, RG_gateway_name ) time.sleep(1) if rg_proc.poll() is not None: raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll())) # should cause the RG to get updated that there's a new gateway gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) random_part = hex(random.randint(0, 2**32-1))[2:] output_path = "/put-%s" % random_part exitcode, out = testlib.run( PUT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, local_path, output_path ) testlib.save_output( output_dir, "syndicate-put", out ) if exitcode != 0: raise Exception("%s exited %s" % (PUT_PATH, exitcode)) # read the file, to populate the cache exitcode, out = testlib.run( CAT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, output_path, valgrind=True ) if exitcode != 0: rg_exitcode, rg_out = testlib.stop_gateway( rg_proc, rg_out_path ) testlib.save_output( output_dir, "syndicate-rg", rg_out ) raise Exception("Failed to read %s" % path)
class Solution: def __init__(self, fn: Callable[[int], bool] = None): if fn is not None: self.fn = fn else: self.fn = isBadVersion def firstBadVersion(self, n: int) -> int: start = 1 end = n while start < end: guess = (start + end) // 2 if self.fn(guess): end = guess else: start = guess + 1 return start def isBadVersion(n: int) -> bool: return n >= 4 if __name__ == "__main__": testdata = [(lambda x: x >= 4, 5, 4)] testlib.run( lambda t, tc: t.assertEqual( Solution(tc[0]).firstBadVersion(tc[1]), tc[2], tc), testdata, )
AG_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "AG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) testlib.update_gateway( config_dir, AG_gateway_name, "port=31112", "driver=%s" % AG_DRIVER ) ag_proc, ag_out_path = testlib.start_gateway( config_dir, AG_PATH, testconf.SYNDICATE_ADMIN, volume_name, AG_gateway_name, valgrind=True ) time.sleep(20) if ag_proc.poll() is not None: ag_exitcode, ag_out = testlib.stop_gateway( ag_proc, ag_out_path ) testlib.save_output(output_dir, "syndicate-ag", ag_out) raise Exception("%s exited %s" % (AG_PATH, ag_proc.poll())) # should cause the AG to get updated that there's a new gateway ug_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN ) # remove inner dir, and have the AG refresh shutil.rmtree(rmdir) exitcode, out = testlib.run( REFRESH_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', ug_gateway_name, '/to_remove_1', valgrind=True ) testlib.save_output( output_dir, "syndicate-refresh", out ) if exitcode != 0: ag_exitcode, ag_out = testlib.stop_gateway( ag_proc, ag_out_path ) testlib.save_output(output_dir, "syndicate-ag", ag_out) raise Exception("syndicate-refresh exit code %s" % exitcode) if "Failed to refresh" in out: ag_exitcode, ag_out = testlib.stop_gateway( ag_proc, ag_out_path ) testlib.save_output(output_dir, "syndicate-ag", ag_out) raise Exception("syndicate-refresh failed") # wait for AG to sync time.sleep(10)
def run(self): # try reading various ranges (these are (start, end) absolute ranges, not offset/length) ranges = [(0, 16384), (1, 200), (0, 4096), (0, 8192), (0, 1000), (0, 6000), (100, 4000), (5000, 10000), (4096, 10000), (5000, 8192), (4096, 16834), (5000, 16384), (4096, 16000), (5000, 16000)] self.exitcode = 0 for (start, end) in ranges: if self.errors: break # only clear reader's cache testlib.clear_cache(self.config_dir, volume_id=self.volume_id, gateway_id=self.read_gateway_id) for i in xrange(0, 2): if self.errors: break exitcode, out = testlib.run(READ_PATH, '-d2', '-f', '-c', os.path.join( self.config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', self.volume_name, '-g', self.read_gateway_name, self.output_path, start, end - start, valgrind=True) out_name = "uncached" if i > 0: out_name = "cached" testlib.save_output( self.output_dir, 'syndicate-read-thread-%s-%s-%s-%s' % (self.get_ident(), start, end, out_name), out) if exitcode != 0: self.exitcode = exitcode self.errormsg = "syndicate-read exit code %s on %s-%s-%s" % ( exitcode, start, end, out_name) break # correctness if expected_data[start:end] not in out: self.exitcode = -1 self.errormsg = "Thread %s missing data for %s-%s-%s" % ( self.get_ident(), start, end, out_name) break if self.exitcode != 0: break return
(5000, 8192), # 2 blocks, head unalighed (4096, 16834), # 3 blocks, aligned (5000, 16384), # 3 blocks, head unaligned (4096, 16000), # 3 blocks, tail unaligned (5000, 16000), # 3 blocks, head and tail unaligned ] for (start, end) in ranges: # only clear reader's cache testlib.clear_cache( config_dir, volume_id=volume_id, gateway_id=read_gateway_id ) # do each read twice--once uncached, and one cached for i in xrange(0, 2): exitcode, out = testlib.run( READ_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', read_gateway_name, output_path, start, end - start, valgrind=True ) out_name = "uncached" if i > 0: out_name = "cached" testlib.save_output( output_dir, 'syndicate-read-%s-%s-%s' % (start, end, out_name), out ) if exitcode != 0: stop_and_save( output_dir, ag_proc, ag_out_path, "syndicate-ag") raise Exception("%s exited %s" % (READ_PATH, exitcode)) # correctness if expected_data[start:end] not in out: stop_and_save( output_dir, ag_proc, ag_out_path, "syndicate-ag") raise Exception("Missing data for %s-%s" % (start, end))
# look up RG rg_gateway_info = testlib.read_gateway( config_dir, RG_gateway_name ) rg_gateway_id = rg_gateway_info['g_id'] volume_info = testlib.read_volume( config_dir, volume_name ) volume_id = volume_info['volume_id'] random_part = hex(random.randint(0, 2**32-1))[2:] output_paths = [] # make NUM_FILES files for i in xrange(0, NUM_FILES): output_path = "/put-%s-%s" % (random_part, i) output_paths.append(output_path) exitcode, out = testlib.run( PUT_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, local_path, output_path, valgrind=True ) testlib.save_output( output_dir, "syndicate-put-%s" % i, out ) if exitcode != 0: stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (PUT_PATH, exitcode)) # rename file i to overwrite file i+1 for i in xrange(0, NUM_FILES, 2): input_path = output_paths[i] output_path = output_paths[i+1] # rename into the same directory or into the new directory exitcode, out = testlib.run( RENAME_PATH, '-d2', '-f', '-c', os.path.join(config_dir, "syndicate.conf"), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, input_path, output_path, valgrind=True ) testlib.save_output( output_dir, "syndicate-rename-%s" % i, out )
"UG", caps="ALL", email=testconf.SYNDICATE_ADMIN) for rep in xrange(0, NUM_REPS): # touch $NUM_FILES files random_part = hex(random.randint(0, 2**32 - 1))[2:] expected_paths = [] for i in xrange(0, NUM_FILES): output_path = "/touch-%s-%s" % (random_part, i) expected_paths.append(output_path) exitcode, out = testlib.run(TOUCH_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, *expected_paths) testlib.save_output(output_dir, "syndicate-touch-%s" % rep, out) if exitcode != 0: stop_and_save(output_dir, rg_proc, rg_out_path, "syndicate-rg") raise Exception("%s exited %s" % (TOUCH_PATH, exitcode)) # list them exitcode, out = testlib.run(LS_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, '/') testlib.save_output(output_dir, "syndicate-ls-full-%s" % rep, out) if exitcode != 0: stop_and_save(output_dir, rg_proc, rg_out_path, "syndicate-rg")
if a[1] < b[0]: i_a += 1 continue if b[1] < a[0]: i_b += 1 continue start = max(a[0], b[0]) end = min(a[1], b[1]) if out and start == out[-1][1]: out[-1][1] = end else: out.append([start, end]) if a[1] < b[1]: i_a += 1 else: i_b += 1 return out if __name__ == "__main__": testdata = [( [[0, 2], [5, 10], [13, 23], [24, 25]], [[1, 5], [8, 12], [15, 24], [25, 26]], [[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]], )] testlib.run( lambda t, tc: t.assertEqual( Solution().intervalIntersection(tc[0], tc[1]), tc[2], tc), testdata, )
sys.modules.update({'sanlock': FakeSanlock()}) def findRemove(listR, value): """used to test if a value exist, if it is, return true and remove it.""" try: listR.remove(value) return True except ValueError: return False def panicMock(msg): msg = "Panic: %s" % (msg) raise AssertionError(msg) if __name__ == '__main__': if "--help" in sys.argv: print("testrunner options:\n" "--local-modules use vdsm modules from source tree, " "instead of installed ones.\n") if findRemove(sys.argv, "--local-modules"): from vdsm import constants constants.P_VDSM = "../vdsm/" # Mock panic() calls for tests utils.panic = panicMock testlib.run()
return ans * ans if __name__ == "__main__": testdata = [ ( [ ["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"], ["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"], ], 4, ), ( [ ["0", "0", "0", "1"], ["1", "1", "0", "1"], ["1", "1", "1", "1"], ["0", "1", "1", "1"], ["0", "1", "1", "1"], ], 9, ), ] testlib.run( lambda t, tc: t.assertEqual(Solution().maximalSquare(tc[0]), tc[1], tc ), testdata, )