repo_name
stringlengths
7
65
path
stringlengths
5
185
copies
stringlengths
1
4
size
stringlengths
4
6
content
stringlengths
977
990k
license
stringclasses
14 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.4
line_max
int64
31
999
alpha_frac
float64
0.25
0.95
ratio
float64
1.5
7.84
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
keon/algorithms
algorithms/graph/traversal.py
1
1319
""" Different ways to traverse a graph """ # dfs and bfs are the ultimately same except that they are visiting nodes in # different order. To simulate this ordering we would use stack for dfs and # queue for bfs. # def dfs_traverse(graph, start): """ Traversal by depth first search. """ visited, stack = set(), [start] while stack: node = stack.pop() if node not in visited: visited.add(node) for next_node in graph[node]: if next_node not in visited: stack.append(next_node) return visited def bfs_traverse(graph, start): """ Traversal by breadth first search. """ visited, queue = set(), [start] while queue: node = queue.pop(0) if node not in visited: visited.add(node) for next_node in graph[node]: if next_node not in visited: queue.append(next_node) return visited def dfs_traverse_recursive(graph, start, visited=None): """ Traversal by recursive depth first search. """ if visited is None: visited = set() visited.add(start) for next_node in graph[start]: if next_node not in visited: dfs_traverse_recursive(graph, next_node, visited) return visited
mit
73c766eff9b9699a113bad6665687066
26.479167
76
0.59439
3.972892
false
false
false
false
keon/algorithms
algorithms/graph/minimum_spanning_tree.py
1
4809
""" Minimum spanning tree (MST) is going to use an undirected graph """ import sys # pylint: disable=too-few-public-methods class Edge: """ An edge of an undirected graph """ def __init__(self, source, target, weight): self.source = source self.target = target self.weight = weight class DisjointSet: """ The disjoint set is represented with an list <n> of integers where <n[i]> is the parent of the node at position <i>. If <n[i]> = <i>, <i> it's a root, or a head, of a set """ def __init__(self, size): """ Args: n (int): Number of vertices in the graph """ self.parent = [None] * size # Contains wich node is the parent of the node at poisition <i> self.size = [1] * size # Contains size of node at index <i>, used to optimize merge for i in range(size): self.parent[i] = i # Make all nodes his own parent, creating n sets. def merge_set(self, node1, node2): """ Args: node1, node2 (int): Indexes of nodes whose sets will be merged. """ # Get the set of nodes at position <a> and <b> # If <a> and <b> are the roots, this will be constant O(1) node1 = self.find_set(node1) node2 = self.find_set(node2) # Join the shortest node to the longest, minimizing tree size (faster find) if self.size[node1] < self.size[node2]: self.parent[node1] = node2 # Merge set(a) and set(b) self.size[node2] += self.size[node1] # Add size of old set(a) to set(b) else: self.parent[node2] = node1 # Merge set(b) and set(a) self.size[node1] += self.size[node2] # Add size of old set(b) to set(a) def find_set(self, node): """ Get the root element of the set containing <a> """ if self.parent[node] != node: # Very important, memoize result of the # recursion in the list to optimize next # calls and make this operation practically constant, O(1) self.parent[node] = self.find_set(self.parent[node]) # node <a> it's the set root, so we can return that index return self.parent[node] def kruskal(vertex_count, edges, forest): """ Args: vertex_count (int): Number of vertices in the graph edges (list of Edge): Edges of the graph forest (DisjointSet): DisjointSet of the vertices Returns: int: sum of weights of the minnimum spanning tree Kruskal algorithm: This algorithm will find the optimal graph with less edges and less total weight to connect all vertices (MST), the MST will always contain n-1 edges because it's the minimum required to connect n vertices. Procedure: Sort the edges (criteria: less weight). Only take edges of nodes in different sets. If we take a edge, we need to merge the sets to discard these. After repeat this until select n-1 edges, we will have the complete MST. """ edges.sort(key=lambda edge: edge.weight) mst = [] # List of edges taken, minimum spanning tree for edge in edges: set_u = forest.find_set(edge.u) # Set of the node <u> set_v = forest.find_set(edge.v) # Set of the node <v> if set_u != set_v: forest.merge_set(set_u, set_v) mst.append(edge) if len(mst) == vertex_count-1: # If we have selected n-1 edges, all the other # edges will be discarted, so, we can stop here break return sum([edge.weight for edge in mst]) def main(): """ Test. How input works: Input consists of different weighted, connected, undirected graphs. line 1: integers n, m lines 2..m+2: edge with the format -> node index u, node index v, integer weight Samples of input: 5 6 1 2 3 1 3 8 2 4 5 3 4 2 3 5 4 4 5 6 3 3 2 1 20 3 1 20 2 3 100 Sum of weights of the optimal paths: 14, 40 """ for size in sys.stdin: vertex_count, edge_count = map(int, size.split()) forest = DisjointSet(edge_count) edges = [None] * edge_count # Create list of size <m> # Read <m> edges from input for i in range(edge_count): source, target, weight = map(int, input().split()) source -= 1 # Convert from 1-indexed to 0-indexed target -= 1 # Convert from 1-indexed to 0-indexed edges[i] = Edge(source, target, weight) # After finish input and graph creation, use Kruskal algorithm for MST: print("MST weights sum:", kruskal(vertex_count, edges, forest)) if __name__ == "__main__": main()
mit
be397cc4942e0dadb1033ecc9e56d5ad
30.847682
99
0.585569
3.716383
false
false
false
false
keon/algorithms
algorithms/maths/power.py
1
1046
""" Performs exponentiation, similarly to the built-in pow() or ** functions. Allows also for calculating the exponentiation modulo. """ def power(a: int, n: int, mod: int = None): """ Iterative version of binary exponentiation Calculate a ^ n if mod is specified, return the result modulo mod Time Complexity : O(log(n)) Space Complexity : O(1) """ ans = 1 while n: if n & 1: ans = ans * a a = a * a if mod: ans %= mod a %= mod n >>= 1 return ans def power_recur(a: int, n: int, mod: int = None): """ Recursive version of binary exponentiation Calculate a ^ n if mod is specified, return the result modulo mod Time Complexity : O(log(n)) Space Complexity : O(log(n)) """ if n == 0: ans = 1 elif n == 1: ans = a else: ans = power_recur(a, n // 2, mod) ans = ans * ans if n % 2: ans = ans * a if mod: ans %= mod return ans
mit
8148d2ba4679f45f28c035947d12ac7c
20.791667
73
0.521033
3.521886
false
false
false
false
keon/algorithms
algorithms/maths/chinese_remainder_theorem.py
1
1557
""" Solves system of equations using the chinese remainder theorem if possible. """ from typing import List from algorithms.maths.gcd import gcd def solve_chinese_remainder(nums : List[int], rems : List[int]): """ Computes the smallest x that satisfies the chinese remainder theorem for a system of equations. The system of equations has the form: x % nums[0] = rems[0] x % nums[1] = rems[1] ... x % nums[k - 1] = rems[k - 1] Where k is the number of elements in nums and rems, k > 0. All numbers in nums needs to be pariwise coprime otherwise an exception is raised returns x: the smallest value for x that satisfies the system of equations """ if not len(nums) == len(rems): raise Exception("nums and rems should have equal length") if not len(nums) > 0: raise Exception("Lists nums and rems need to contain at least one element") for num in nums: if not num > 1: raise Exception("All numbers in nums needs to be > 1") if not _check_coprime(nums): raise Exception("All pairs of numbers in nums are not coprime") k = len(nums) x = 1 while True: i = 0 while i < k: if x % nums[i] != rems[i]: break i += 1 if i == k: return x x += 1 def _check_coprime(list_to_check : List[int]): for ind, num in enumerate(list_to_check): for num2 in list_to_check[ind + 1:]: if gcd(num, num2) != 1: return False return True
mit
e6565651bba4bd15572f7c996851bfcd
32.847826
85
0.597303
3.663529
false
false
false
false
bxlab/bx-python
lib/bx/align/axt.py
1
7619
""" Support for reading and writing the `AXT`_ format used for pairwise alignments. .. _AXT: http://genome.ucsc.edu/goldenPath/help/axt.html """ from bx import interval_index_file from bx.align import ( Alignment, Component, src_split, ) # Tools for dealing with pairwise alignments in AXT format class MultiIndexed: """Similar to 'indexed' but wraps more than one axt_file""" def __init__(self, axt_filenames, keep_open=False): self.indexes = [Indexed(axt_file, axt_file + ".index") for axt_file in axt_filenames] def get(self, src, start, end): blocks = [] for index in self.indexes: blocks += index.get(src, start, end) return blocks class Indexed: """Indexed access to a axt using overlap queries, requires an index file""" def __init__( self, axt_filename, index_filename=None, keep_open=False, species1=None, species2=None, species_to_lengths=None, support_ids=False, ): if index_filename is None: index_filename = axt_filename + ".index" self.indexes = interval_index_file.Indexes(filename=index_filename) self.axt_filename = axt_filename # nota bene: (self.species1 = species1 or "species1") is incorrect if species1="" self.species1 = species1 if self.species1 is None: self.species1 = "species1" self.species2 = species2 if self.species2 is None: self.species2 = "species2" self.species_to_lengths = species_to_lengths self.support_ids = support_ids # for extra text at end of axt header lines if keep_open: self.f = open(axt_filename) else: self.f = None def get(self, src, start, end): intersections = self.indexes.find(src, start, end) return (self.get_axt_at_offset(val) for start, end, val in intersections) def get_axt_at_offset(self, offset): if self.f: self.f.seek(offset) return read_next_axt(self.f, self.species1, self.species2, self.species_to_lengths, self.support_ids) else: f = open(self.axt_filename) try: f.seek(offset) return read_next_axt(f, self.species1, self.species2, self.species_to_lengths, self.support_ids) finally: f.close() class Reader: """Iterate over all axt blocks in a file in order""" def __init__(self, file, species1=None, species2=None, species_to_lengths=None, support_ids=False): self.file = file # nota bene: (self.species1 = species1 or "species1") is incorrect if species1="" self.species1 = species1 if self.species1 is None: self.species1 = "species1" self.species2 = species2 if self.species2 is None: self.species2 = "species2" self.species_to_lengths = species_to_lengths self.support_ids = support_ids # for extra text at end of axt header lines self.attributes = {} def __next__(self): return read_next_axt(self.file, self.species1, self.species2, self.species_to_lengths, self.support_ids) def __iter__(self): return ReaderIter(self) def close(self): self.file.close() class ReaderIter: def __init__(self, reader): self.reader = reader def __iter__(self): return self def __next__(self): v = next(self.reader) if not v: raise StopIteration return v class Writer: def __init__(self, file, attributes=None): if attributes is None: attributes = {} self.file = file self.block = 0 self.src_split = True if "src_split" in attributes: self.src_split = attributes["src_split"] def write(self, alignment): if len(alignment.components) != 2: raise ValueError("%d-component alignment is not compatible with axt" % len(alignment.components)) c1 = alignment.components[0] c2 = alignment.components[1] if c1.strand != "+": c1 = c1.reverse_complement() c2 = c2.reverse_complement() if self.src_split: spec1, chr1 = src_split(c1.src) spec2, chr2 = src_split(c2.src) else: chr1, chr2 = c1.src, c2.src self.file.write( "%d %s %d %d %s %d %d %s %s\n" % ( self.block, chr1, c1.start + 1, c1.start + c1.size, chr2, c2.start + 1, c2.start + c2.size, c2.strand, alignment.score, ) ) self.file.write("%s\n" % c1.text) self.file.write("%s\n" % c2.text) self.file.write("\n") self.block += 1 def close(self): self.file.close() # ---- Helper methods --------------------------------------------------------- # typical axt block: # 0 chr19 3001012 3001075 chr11 70568380 70568443 - 3500 [optional text] # TCAGCTCATAAATCACCTCCTGCCACAAGCCTGGCCTGGTCCCAGGAGAGTGTCCAGGCTCAGA # TCTGTTCATAAACCACCTGCCATGACAAGCCTGGCCTGTTCCCAAGACAATGTCCAGGCTCAGA # start and stop are origin-1, inclusive # first species is always on plus strand # when second species is on minus strand, start and stop are counted from sequence end def read_next_axt(file, species1, species2, species_to_lengths=None, support_ids=False): line = readline(file, skip_blank=True) if not line: return fields = line.split() if len(fields) < 9 or (not support_ids and len(fields) > 9): raise ValueError("bad axt-block header: %s" % line) attributes = {} if len(fields) > 9: attributes["id"] = "_".join(fields[9:]) seq1 = readline(file) if not line or line.isspace(): raise ValueError("incomplete axt-block; header: %s" % line) seq2 = readline(file) if not line or line.isspace(): raise ValueError("incomplete axt-block; header: %s" % line) # Build 2 component alignment alignment = Alignment(attributes=attributes, species_to_lengths=species_to_lengths) # Build component for species 1 component = Component() component.src = fields[1] if species1 != "": component.src = species1 + "." + component.src # axt intervals are origin-1 and inclusive on both ends component.start = int(fields[2]) - 1 end = int(fields[3]) component.size = end - component.start component.strand = "+" component.text = seq1.strip() alignment.add_component(component) # Build component for species 2 component = Component() component.src = fields[4] if species2 != "": component.src = species2 + "." + component.src component.start = int(fields[5]) - 1 end = int(fields[6]) component.size = end - component.start component.strand = fields[7] component.text = seq2.strip() alignment.add_component(component) # add score try: alignment.score = int(fields[8]) except ValueError: try: alignment.score = float(fields[8]) except ValueError: alignment.score = fields[8] return alignment def readline(file, skip_blank=False): """Read a line from provided file, skipping any blank or comment lines""" while True: line = file.readline() if not line: return None if line[0] != "#" and not (skip_blank and line.isspace()): return line
mit
8bd92d6f00d3eae0789071315299f9cb
31.012605
113
0.590891
3.678899
false
false
false
false
bxlab/bx-python
lib/bx/intervals/operations/concat.py
1
2602
""" Concatenate sets of intervals. Preserves format of the first input -- it is possible to concat two files that have different column orders. Of course, the meta-data of the second will be lost (and filled with a "."). If all of the files (GenomicInteralReaders) are the same format, sameformat=True will preserve all columns of the first input, cuts extra columns on subsequent input, and pads missing columns. If sameformat=False then extra columns are filled with ".". """ from bx.intervals.io import GenomicInterval from bx.tabular.io import ( Comment, Header, ) def concat(readers, comments=True, header=True, sameformat=True): # Save columns from the first input chrom_col = readers[0].chrom_col start_col = readers[0].start_col end_col = readers[0].end_col strand_col = readers[0].strand_col nfields = None firstdataset = True output = False for intervals in readers: for interval in intervals: if isinstance(interval, GenomicInterval): if not nfields: nfields = interval.nfields out_interval = interval.copy() if sameformat or firstdataset: # everything except the first input has to be # trimmed or padded to match the first input if len(out_interval.fields) > nfields: out_interval.fields = out_interval.fields[0:nfields] while len(out_interval.fields) < nfields: out_interval.fields.append(".") output = True yield out_interval else: chrom = out_interval.chrom start = out_interval.start end = out_interval.end strand = out_interval.strand out_interval.fields = ["." for col in range(nfields)] out_interval.fields[chrom_col] = chrom out_interval.fields[start_col] = str(start) out_interval.fields[end_col] = str(end) # Strand is optional, might not exist in output if strand_col < len(out_interval.fields): out_interval.fields[strand_col] = strand yield out_interval elif isinstance(interval, Header) and header: yield interval elif isinstance(interval, Comment) and comments: yield interval if output and firstdataset: firstdataset = False
mit
0c340624c6a7b168f12cdd4660941438
41.655738
78
0.581091
4.580986
false
false
false
false
bxlab/bx-python
scripts/mMK_bitset.py
1
5170
#!/usr/bin/env python from optparse import OptionParser from rpy import r import bx.align.maf import bx.bitset from bx.bitset_builders import binned_bitsets_from_file def main(): parser = OptionParser(usage="usage: %prog [options] maf_file snp_file neutral_file window_size step_size") parser.add_option("-o", "--outfile", help="Specify file for output") parser.add_option("-s", "--species", type="string", default="panTro2") parser.add_option("-b", "--build", type="string", default="hg18") (options, args) = parser.parse_args() if len(args) != 5: parser.error("Incorrect number of arguments") else: maf_filename = args[0] snp_filename = args[1] neutral_filename = args[2] window_size = int(args[3]) step_size = int(args[4]) if options.outfile is not None: out_file = open(options.outfile, "w") # Generate snp and neutral bitsets AR_snp_bitsets = binned_bitsets_from_file(open(snp_filename)) neutral_bitsets = binned_bitsets_from_file(open(neutral_filename)) # Generate divergence bitset from maf file AR_div_bitsets = dict() chr_lens = dict() reader = bx.align.maf.Reader(open(maf_filename)) for block in reader: comp1 = block.get_component_by_src_start(options.build) comp2 = block.get_component_by_src_start(options.species) if comp1 is None or comp2 is None: continue # Chromosome, start, and stop of reference species alignment chr = comp1.src.split(".")[1] start = comp1.start # Get or create bitset for this chromosome if chr in AR_div_bitsets: bitset = AR_div_bitsets[chr] else: bitset = AR_div_bitsets[chr] = bx.bitset.BinnedBitSet() chr_lens[chr] = comp1.get_src_size() # Iterate over text and set diverged bit pos = start for ch1, ch2 in zip(comp1.text.upper(), comp2.text.upper()): if ch1 == "-": continue if ch2 == "-": pos += 1 continue if ch1 != ch2 and not AR_snp_bitsets[chr][pos]: bitset.set(pos) pos += 1 # Copy div and snp bitsets nonAR_snp_bitsets = dict() for chr in AR_snp_bitsets: nonAR_snp_bitsets[chr] = bx.bitset.BinnedBitSet() nonAR_snp_bitsets[chr].ior(AR_snp_bitsets[chr]) nonAR_div_bitsets = dict() for chr in AR_div_bitsets: nonAR_div_bitsets[chr] = bx.bitset.BinnedBitSet() nonAR_div_bitsets[chr].ior(AR_div_bitsets[chr]) # Generates AR snps by intersecting with neutral intervals for chr in AR_snp_bitsets: AR_snp_bitsets[chr].iand(neutral_bitsets[chr]) # Generates AR divs by intersecting with neutral intervals for chr in AR_div_bitsets: AR_div_bitsets[chr].iand(neutral_bitsets[chr]) # Inverts the neutral intervals so now represents nonAR for chr in neutral_bitsets: neutral_bitsets[chr].invert() # Generates nonAR snps by intersecting with masked neutral intervals for chr in nonAR_snp_bitsets: nonAR_snp_bitsets[chr].iand(neutral_bitsets[chr]) # Generates nonAR divs by intersecting with masked neutral intervals for chr in nonAR_div_bitsets: nonAR_div_bitsets[chr].iand(neutral_bitsets[chr]) for chr in AR_div_bitsets: for window in range(0, chr_lens[chr] - window_size, step_size): # neutral_size = neutral_bitsets[chr].count_range(window, window_size) # if neutral_size < 9200: continue AR_snp = AR_snp_bitsets[chr].count_range(window, window_size) AR_div = AR_div_bitsets[chr].count_range(window, window_size) nonAR_snp = nonAR_snp_bitsets[chr].count_range(window, window_size) nonAR_div = nonAR_div_bitsets[chr].count_range(window, window_size) if nonAR_snp >= 6 and nonAR_div >= 6 and AR_snp >= 6 and AR_div >= 6: MK_pval = MK_chi_pvalue(nonAR_snp, nonAR_div, AR_snp, AR_div) else: MK_pval = MK_fisher_pvalue(nonAR_snp, nonAR_div, AR_snp, AR_div) if options.outfile is not None: out_file.write( "%s\t%d\t%d\t%d\t%d\t%d\t%d\t%1.15f\n" % (chr, window, window + window_size, nonAR_snp, nonAR_div, AR_snp, AR_div, MK_pval) ) else: print( "%s\t%d\t%d\t%d\t%d\t%d\t%d\t%1.15f" % (chr, window, window + window_size, nonAR_snp, nonAR_div, AR_snp, AR_div, MK_pval) ) if options.outfile is not None: out_file.close() def MK_fisher_pvalue(win_snp, win_div, AR_snp, AR_div): if win_snp == 0 and win_div == 0 and AR_snp == 0 and AR_div == 0: return 1.0 fisher_result = r.fisher_test(r.matrix(r.c([win_snp, win_div, AR_snp, AR_div]), nr=2)) return fisher_result["p.value"] def MK_chi_pvalue(win_snp, win_div, AR_snp, AR_div): chi_result = r.chisq_test(r.matrix(r.c([win_snp, win_div, AR_snp, AR_div]), nr=2)) return chi_result["p.value"] main()
mit
72dde494e9533515a0bcd3c6f462fbae
34.170068
110
0.600193
3.057363
false
false
false
false
bxlab/bx-python
scripts/maf_to_axt.py
1
2743
#!/usr/bin/env python """ Application to convert MAF file to AXT file, projecting to any two species. Reads a MAF file from standard input and writes an AXT file to standard out; some statistics are written to standard error. The user must specify the two species of interest. usage: %prog primary_species secondary_species < maf_file > axt_file """ __author__ = "Bob Harris (rsharris@bx.psu.edu)" import copy import sys import bx.align.axt import bx.align.maf def usage(s=None): message = """ maf_to_axt primary_species secondary_species < maf_file > axt_file """ if s is None: sys.exit(message) else: sys.exit(f"{s}\n{message}") def main(): primary = None secondary = None args = sys.argv[1:] while len(args) > 0: arg = args.pop(0) val = None fields = arg.split("=", 1) if len(fields) == 2: arg = fields[0] val = fields[1] if val == "": usage("missing a value in %s=" % arg) if primary is None and val is None: primary = arg elif secondary is None and val is None: secondary = arg else: usage("unknown argument: %s" % arg) if primary is None: usage("missing primary species") if secondary is None: usage("missing secondary species") # read the alignments and other info out = bx.align.axt.Writer(sys.stdout) axtsRead = 0 mafsWritten = 0 for mafBlock in bx.align.maf.Reader(sys.stdin): axtsRead += 1 p = mafBlock.get_component_by_src_start(primary) if p is None: continue s = mafBlock.get_component_by_src_start(secondary) if s is None: continue axtBlock = bx.align.Alignment(mafBlock.score, mafBlock.attributes) axtBlock.add_component(clone_component(p)) axtBlock.add_component(clone_component(s)) remove_mutual_gaps(axtBlock) if axtBlock.text_size == 0: continue out.write(axtBlock) mafsWritten += 1 sys.stderr.write("%d blocks read, %d written\n" % (axtsRead, mafsWritten)) def clone_component(c): return bx.align.Component(c.src, c.start, c.size, c.strand, c.src_size, copy.copy(c.text)) def remove_mutual_gaps(block): if len(block.components) == 0: return nonGaps = [] for c in block.components: for ix in range(0, block.text_size): if ix not in nonGaps and c.text[ix] != "-": nonGaps.append(ix) nonGaps.sort() for c in block.components: c.text = "".join([c.text[ix] for ix in nonGaps]) block.text_size = len(nonGaps) if __name__ == "__main__": main()
mit
bf006bb079326b344c23bb63e27267f7
23.274336
94
0.595334
3.394802
false
false
false
false
bxlab/bx-python
scripts/maf_count.py
1
1622
#!/usr/bin/env python """ Read a MAF from standard input and print counts of alignments, bases, or columns. usage: %prog [options] -c, --cols: count alignment columns rather than number of alignments -b, --bases: count bases in first species rather than number of alignments -s, --skip=N: when counting bases, skip this base -e, --each: print a count for each alignment rather than whole file -r, --ref=N: reference sequence (first by default, 0..n) """ import sys import bx.align.maf from bx.cookbook import doc_optparse def __main__(): options, args = doc_optparse.parse(__doc__) try: if options.cols: action = "cols" elif options.bases: action = "bases" else: action = "aligns" print_each = bool(options.each) if options.ref: ref = int(options.ref) else: ref = 0 if options.skip: skip = options.skip else: skip = None except Exception: doc_optparse.exit() maf_reader = bx.align.maf.Reader(sys.stdin) count = 0 for m in maf_reader: if action == "aligns": count += 1 elif action == "cols": count += m.text_size elif action == "bases": if skip: count += m.components[ref].size - m.components[ref].text.count(skip) else: count += m.components[ref].size if print_each: print(count) count = 0 if not print_each: print(count) if __name__ == "__main__": __main__()
mit
46212d8db3b3ac751b543542ba7b574c
22.852941
84
0.548089
3.807512
false
false
false
false
bxlab/bx-python
scripts/maf_tile.py
1
4303
#!/usr/bin/env python """ 'Tile' the blocks of a maf file over each of a set of intervals. The highest scoring block that covers any part of a region will be used, and pieces not covered by any block filled with "-" or optionally "*". The list of species to tile is specified by `tree` (either a tree or just a comma separated list). The `seq_db` is a lookup table mapping chromosome names to nib file for filling in the reference species. Maf files must be indexed. NOTE: See maf_tile_2.py for a more sophisticated version of this program, I think this one will be eliminated in the future. usage: %prog tree maf_files... -m, --missingData: Inserts wildcards for missing block rows instead of '-' """ import sys import bx.align as align import bx.align.maf import bx.seq.nib from bx.cookbook import doc_optparse tree_tx = str.maketrans("(),", " ") def main(): options, args = doc_optparse.parse(__doc__) try: sources = args[0].translate(tree_tx).split() seq_db = load_seq_db(args[1]) index = bx.align.maf.MultiIndexed(args[2:]) out = bx.align.maf.Writer(sys.stdout) missing_data = bool(options.missingData) except Exception: doc_optparse.exception() for line in sys.stdin: ref_src, start, end = line.split()[0:3] do_interval(sources, index, out, ref_src, int(start), int(end), seq_db, missing_data) out.close() def load_seq_db(fname): db = {} for line in open(fname): fields = line.split(",") src = fields[1] + "." + fields[2] seq = fields[4] db[src] = seq.strip() return db def do_interval(sources, index, out, ref_src, start, end, seq_db, missing_data): assert sources[0].split(".")[0] == ref_src.split(".")[0], "{} != {}".format( sources[0].split(".")[0], ref_src.split(".")[0] ) base_len = end - start blocks = index.get(ref_src, start, end) # From low to high score blocks.sort(key=lambda _: _.score) mask = [-1] * base_len ref_src_size = None for i, block in enumerate(blocks): ref = block.get_component_by_src_start(ref_src) ref_src_size = ref.src_size assert ref.strand == "+" slice_start = max(start, ref.start) slice_end = min(end, ref.end) for j in range(slice_start, slice_end): mask[j - start] = i tiled = [] for i in range(len(sources)): tiled.append([]) for ss, ee, index in intervals_from_mask(mask): if index < 0: tiled[0].append(bx.seq.nib.NibFile(open(seq_db[ref_src])).get(start + ss, ee - ss)) for row in tiled[1:]: if missing_data: row.append("*" * (ee - ss)) else: row.append("-" * (ee - ss)) else: slice_start = start + ss slice_end = start + ee block = blocks[index] ref = block.get_component_by_src_start(ref_src) sliced = block.slice_by_component(ref, slice_start, slice_end) sliced = sliced.limit_to_species(sources) sliced.remove_all_gap_columns() for i, src in enumerate(sources): comp = sliced.get_component_by_src_start(src) if comp: tiled[i].append(comp.text) else: if missing_data: tiled[i].append("*" * sliced.text_size) else: tiled[i].append("-" * sliced.text_size) a = align.Alignment() for i, name in enumerate(sources): text = "".join(tiled[i]) size = len(text) - text.count("-") if i == 0: if ref_src_size is None: ref_src_size = bx.seq.nib.NibFile(open(seq_db[ref_src])).length c = align.Component(ref_src, start, end - start, "+", ref_src_size, text) else: c = align.Component(name + ".fake", 0, size, "?", size, text) a.add_component(c) out.write(a) def intervals_from_mask(mask): start = 0 last = mask[0] for i in range(1, len(mask)): if mask[i] != last: yield start, i, last start = i last = mask[i] yield start, len(mask), last main()
mit
c35310421e44735956c8c23ded6771ae
30.181159
95
0.558912
3.412371
false
false
false
false
bxlab/bx-python
lib/bx/interval_index_file_tests.py
1
1608
import random from tempfile import mktemp from . import interval_index_file from .interval_index_file import Indexes def test_offsets(): assert interval_index_file.offsets_for_max_size(512 * 1024 * 1024 - 1) == [ 512 + 64 + 8 + 1, 64 + 8 + 1, 8 + 1, 1, 0, ] def test_interval_index_file(): ix = Indexes() chrs = [] for i in range(5): intervals = [] name = "seq%d" % i max = random.randint(0, interval_index_file.MAX) # print name, "size", max for i in range(500): start = random.randint(0, max) end = random.randint(0, max) if end < start: end, start = start, end ix.add(name, start, end, i, max=interval_index_file.MAX) intervals.append((start, end, i)) chrs.append(intervals) fname = mktemp() f = open(fname, "wb") ix.write(f) f.close() del ix ix = Indexes(fname) for i in range(5): intervals = chrs[i] name = "seq%d" % i for i in range(100): start = random.randint(0, max) end = random.randint(0, max) if end < start: end, start = start, end query_intervals = set() for (s, e, i) in intervals: if e > start and s < end: query_intervals.add((s, e, i)) result = ix.find(name, start, end) for inter in result: assert inter in query_intervals def test_zero(): ix = Indexes() ix.add("t.idx", 0, 0, 1, 123)
mit
9d02efd925188b0048ba80687b386f88
25.8
79
0.502488
3.534066
false
false
false
false
bxlab/bx-python
lib/bx/pwm/bed_score_aligned_string.py
1
2951
#!/usr/bin/env python2.4 """ Returns all positions of a maf with any pwm score > threshold The positions are projected onto human coordinates """ import sys from bx import intervals from bx.align import maf as align_maf from bx.pwm.pwm_score_maf import MafMotifScorer def isnan(x): return not x == x def main(): if len(sys.argv) < 5: print("%s bedfile inmaf spec1,spec2,... string [string2,...]" % sys.argv[0], file=sys.stderr) sys.exit(0) # read in intervals regions = {} for line in open(sys.argv[1]): if line.startswith("#"): continue fields = line.strip().split() chrom, start, end = fields[0], int(fields[1]), int(fields[2]) try: name = fields[3] except IndexError: name = None if chrom not in regions: regions[chrom] = intervals.Intersecter() regions[chrom].add(start, end, name) motif_strings = sys.argv[4:] if not isinstance(motif_strings, list): motif_strings = [motif_strings] inmaf = open(sys.argv[2]) threshold = 0.5 species = [] for sp in sys.argv[3].split(","): species.append(sp) for maf in align_maf.Reader(inmaf): mafchrom = maf.components[0].src.split(".")[1] mafstart = maf.components[0].start mafend = maf.components[0].end reftext = maf.components[0].text r = regions[mafchrom].find(mafstart, mafend) if mafchrom not in regions or len(r) == 0: continue # maf block scores for each matrix for scoremax, width, headers in MafMotifScorer(species, maf, motif_strings): blocklength = width mafsrc, mafstart, mafend = headers[0] mafchrom = mafsrc.split(".")[1] # lists of scores for each position in scoremax for mx_name, mx in scoremax.items(): for offset in range(blocklength): # scan all species with threshold for i in range(len(species)): if mx[i][offset] > threshold: refstart = mafstart + offset - reftext.count("-", 0, offset) refend = refstart + len(mx_name) data = " ".join(["%.2f" % mx[x][offset] for x in range(len(species))]) # quote the motif r = regions[mafchrom].find(refstart, refend) if mafchrom in regions and len(r) > 0: region_label = r[0].value else: # region_label = 0 continue v_name = mx_name.replace(" ", "_") print(mafchrom, refstart, refend, region_label, v_name, data) break if __name__ == "__main__": main()
mit
d1ac9e945bee7ce9350a667a26e42083
32.157303
101
0.517452
3.872703
false
false
false
false
bxlab/bx-python
lib/bx/pwm/position_weight_matrix.py
1
30984
#!/usr/bin/env python import math import sys from numpy import ( float32, putmask, shape, zeros, ) # This is the average of all species in the alignment outside of exons # > mean(r) # A T C G # 0.2863776 0.2878264 0.2129560 0.2128400 # > sd(r) # A T C G # 0.01316192 0.01371148 0.01293836 0.01386655 ENCODE_NONCODING_BACKGROUND = {"A": 0.2863776, "T": 0.2878264, "G": 0.2128400, "C": 0.2129560} class Align: def __init__(self, seqrows, headers=None): self.rows = seqrows self.nrows = len(seqrows) ncol = None for rownum, row in enumerate(self.rows): try: if ncol is None: ncol = len(row) elif ncol != len(row): raise ValueError( "Align: __init__:alignment block:row %d does not have %d columns, it has %d" % (rownum, ncol, len(row)) ) except Exception: print(row) raise Exception("") self.ncols = ncol self.dims = (self.nrows, self.ncols) self.headers = headers def __str__(self): return "\n".join(self.rows) class AlignScoreMatrix: def __init__(self, align): nan = float("nan") matrix = zeros((align.nrows, align.ncols), float32) # set to nans for ir in range(len(matrix)): for ic in range(len(matrix[ir])): matrix[ir][ic] = nan self.matrix = matrix def __len__(self): return shape(self.matrix)[1] def __str__(self): print(self.matrix) def score_align_motif(align, motif, gapmask=None, byPosition=True): chr, chr_start, chr_stop = align.headers[0] # a blank score matrix nrows, ncols = align.dims ascoremax = AlignScoreMatrix(align) scoremax = ascoremax.matrix minSeqLen = len(motif) for ir in range(nrows): pass # row is missing data if isnan(align.rows[ir][0]): continue for start in range(ncols): if align.rows[ir][start] == "-": continue elif align.rows[ir][start] == "n": continue elif align.rows[ir][start] == "N": continue # get enough sequence for the weight matrix subseq = "" end = 0 ic = start while len(subseq) < minSeqLen: if ic >= len(align.rows[ir]): break char = align.rows[ir][ic].upper() ic += 1 if char == "-" or char == "N": continue else: subseq += char if len(subseq) == minSeqLen: end = ic + 1 for_score = int(match_consensus(subseq, motif)) revseq = reverse_complement(subseq) rev_score = int(match_consensus(revseq, motif)) score = max(for_score, rev_score) # dbg # if ir == 0: print >>sys.stderr, int(chr_start) + start - align.rows[ir].count('-',0,start), subseq, score # replace the alignment positions with the result if byPosition: scoremax[ir][start] = score else: # replace positions matching the width of the pwm for i in range(start, end): if isnan(scoremax[ir][i]): scoremax[ir][i] = score elif score > scoremax[ir][i]: scoremax[ir][i] = score # break # mask gap characters if gapmask is None: gapmask = score_align_gaps(align) putmask(scoremax, gapmask, float("nan")) return scoremax # ----------- # # WeightMatrix-- # A position weight matrix (PWM) representation of a motif. # # ---------- # construction arguments: # id: id (name) of the motif # rows: the matrix; each row is a hash from symbol to weight, with # .. the weight in string form # alphabet: symbols allowed # background: hash from symbol to background probability of that symbol; if # .. not specified, ENCODE_NONCODING_BACKGROUND is used # internal fields: # rows: the matrix; each row is a hash from symbol to log-odds score # .. of that symbol for that row of the weight matrix # counts: the matrix; count[row][sym] is the weight, as an integer # probs: the matrix; probs[row][sym] is the weight, as an probability # ---------- class PositionWeightMatrix: complementMap = str.maketrans("ACGTacgt", "TGCAtgca") # IUPAC-IUB symbols = { "A": frozenset(["A"]), "C": frozenset(["C"]), "G": frozenset(["G"]), "T": frozenset(["T"]), "R": frozenset(["A", "G"]), "Y": frozenset(["C", "T"]), "M": frozenset(["A", "C"]), "K": frozenset(["G", "T"]), "S": frozenset(["G", "C"]), "W": frozenset(["A", "T"]), "H": frozenset(["A", "C", "T"]), "B": frozenset(["G", "T", "C"]), "V": frozenset(["G", "C", "A"]), "D": frozenset(["G", "T", "A"]), } def __init__(self, id, rows, alphabet, background=None, score_correction=True): self.id = id self.alphabet = alphabet nsymbols = len(self.alphabet) for i in range(len(self.alphabet)): self.alphabet[i] = self.alphabet[i].upper() if background is not None: self.background = background else: self.background = {} sorted_alphabet = [] sorted_alphabet[:] = self.alphabet[:] sorted_alphabet.sort() if ["A", "C", "G", "T"] == sorted_alphabet: self.background = ENCODE_NONCODING_BACKGROUND else: for x in self.alphabet: self.background[x] = float(1) / len(self.alphabet) if score_correction: self.score_correction = self.corrected_probability_score else: self.score_correction = self.simple_probability # partition counts from consensus symbol # in order to properly handle scaling in the presense of non-integers, # we prescan the matrix to figure out the largest scale factor, then go # back through and scale 'em all (some rows may be integer counts, # others may be probabilities) self.consensus = [] scale = 1 for i in range(len(rows)): # try: fields, consensus = rows[i][:nsymbols], rows[i][-1] for x, count in enumerate(fields): try: (w, s) = self.parse_weight(count) except ValueError: raise ValueError("pwm row {} has bad weight {}".format(" ".join(fields), w)) # replace row counts with (values,scale) rows[i][x] = (w, s) scale = max(s, scale) self.consensus.append(consensus) hashRows = [] self.matrix_base_counts = {} # for pseudocounts self.counts = [] # for scaled counts self.probs = [] # for probabilities # scale counts to integers for i in range(len(rows)): hashRows.append(dict()) for x, sym in enumerate(alphabet): (w, s) = rows[i][x] hashRows[i][sym] = w * scale / s assert hashRows[i][sym] >= 0 if sym not in self.matrix_base_counts: self.matrix_base_counts[sym] = 0 self.matrix_base_counts[sym] += hashRows[i][sym] self.counts.append(hashRows[i].copy()) self.probs.append(hashRows[i].copy()) totalWeight = float(sum(self.probs[i].values())) for sym in self.probs[i]: self.probs[i][sym] /= totalWeight self.sites = sum(hashRows[0].values()) # scan pwm to pre-compute logs of probabilities and min and max log-odds # scores (over the whole PWM) for scaling; note that the same min and max # applies for scaling long-odds scores for quantum comparisions self.information_content = [] minSum = 0 maxSum = 0 for i in range(len(hashRows)): self.information_content.append(self.information_content_calculation(i, hashRows)) newHashRow = {} for base in self.alphabet: newHashRow[base] = self.pwm_score(base, i, hashRows) hashRows[i] = newHashRow minSum += min(hashRows[i].values()) maxSum += max(hashRows[i].values()) self.minSum = minSum self.maxSum = maxSum self.rows = hashRows # Reference 1: Wasserman and Sandelin: Nat Rev Genet. 2004 Apr;5(4):276-87. # Reference 2: Gertz et al.: Genome Res. 2005 Aug;15(8):1145-52. def information_content_calculation(self, i, counts): # Reference 1) return 2 + sum(self.information_base_content(base, i, counts) for base in self.alphabet) # Reference 2) # return sum( [ self.information_base_content(base,i,counts) for base in self.alphabet ] ) def information_base_content(self, base, i, counts): # Reference 1) # return self.score_correction(counts,base,i) * math.log ( self.score_correction(counts,base,i), 2) # Reference 2) return self.score_correction(counts, base, i) * self.pwm_score(base, i, counts) def __call__(self, seq): return self.score_seq(seq) def __add__(self, other): assert self.alphabet == other.alphabet r, (p, q) = self.max_correlation(other) if p == q == 0: width = max(len(self), len(other)) elif p > 0: width = max(len(other) + p, len(self)) elif q > 0: width = max(len(self) + q, len(other)) sumx = zeros((width, len(self.alphabet)), dtype="int") selfx = self.to_count_matrix() otherx = other.to_count_matrix() if p == q == 0: sumx[: len(self)] += selfx sumx[: len(other)] += otherx elif p > 0: sumx[p : p + len(other)] += otherx sumx[: len(self)] += selfx else: sumx[: len(other)] += otherx sumx[q : q + len(self)] += selfx newRows = [] for x in sumx: y = list(x) y.append(consensus_symbol(y)) y = [str(yi) for yi in y] newRows.append(y) return PositionWeightMatrix(self.id + other.id, newRows, self.alphabet, self.background) def __old_add__(self, other, maxp=None): assert self.alphabet == other.alphabet bigN = max(len(self), len(other)) smallN = min(len(self), len(other)) if not maxp: prsq = self.correlation(other) maxp = prsq.index(max(prsq)) leftpad = " " * maxp rightsize = bigN - smallN rightpad = " " * rightsize leftStrings = [] rightStrings = [] if len(self) > len(other): larger = self smaller = other leftStrings = self.consensus rightStrings = list(leftpad) + other.consensus + list(rightpad) else: smaller = self larger = other leftStrings = list(leftpad) + self.consensus + list(rightpad) rightStrings = other.consensus sumx = zeros([bigN, len(self.alphabet)]) sumx += larger.to_count_matrix() sumx[maxp : maxp + smallN] += smaller.to_count_matrix() newRows = [] for i, x in enumerate(sumx): y = list(x) y.append(leftStrings[i] + rightStrings[i]) y = [str(yi) for yi in y] newRows.append(y) # return PositionWeightMatrix(self.id+other.id,newRows[maxp:maxp+smallN],self.alphabet,self.background) return PositionWeightMatrix(self.id + other.id, newRows, self.alphabet, self.background) def to_matrix(self): m = zeros([len(self), len(self.alphabet)]) for i in range(len(self)): for j, a in enumerate(self.alphabet): m[i][j] = self[i][a] return m def to_count_matrix(self): m = zeros([len(self), len(self.alphabet)], dtype="int") for i in range(len(self)): for j, a in enumerate(self.alphabet): m[i][j] = self.counts[i][a] return m def max_correlation(self, otherwmx): rsq, ixtuple = self.slide_correlation(otherwmx) max_rsq = max(rsq) maxp, maxq = ixtuple[rsq.index(max_rsq)] return max_rsq, (maxp, maxq) def slide_correlation(self, other): assert self.alphabet == other.alphabet selfx = self.to_count_matrix() otherx = other.to_count_matrix() rsq = [] ixtuple = [] # self staggered over other, scan self backwards until flush for q in range(len(other) - 1, -1, -1): r = 0 n = 0 for p in range(len(self)): if q + p < len(other): r += rsquared(list(selfx[p]), list(otherx[q + p])) n += 1 else: n += 1 rsq.append(r / n) ixtuple.append((0, q)) # other staggered below self , scan other forward for p in range(1, len(self)): r = 0 n = 0 for q in range(len(other)): if p + q < len(self): r += rsquared(list(selfx[p + q]), list(otherx[q])) n += 1 else: n += 1 rsq.append(r / n) ixtuple.append((p, 0)) return rsq, ixtuple def correlation(self, otherwmx): assert self.alphabet == otherwmx.alphabet if len(self) > len(otherwmx): larger = self.to_count_matrix() smaller = otherwmx.to_count_matrix() else: smaller = self.to_count_matrix() larger = otherwmx.to_count_matrix() bigN = len(larger) smallN = len(smaller) position_rsq = [] # slide small over large, for ave rsq for p in range(bigN): if p + smallN <= bigN: r = 0 for q in range(smallN): r += rsquared(list(smaller[q]), list(larger[p + q])) position_rsq.append(r / smallN) return position_rsq def score_align(self, align, gapmask=None, byPosition=True): # a blank score matrix nrows, ncols = align.dims ascoremax = AlignScoreMatrix(align) scoremax = ascoremax.matrix minSeqLen = len(self) for ir in range(nrows): # row is missing data if isnan(align.rows[ir][0]): continue for start in range(ncols): if align.rows[ir][start] == "-": continue elif align.rows[ir][start] == "n": continue elif align.rows[ir][start] == "N": continue # get enough sequence for the weight matrix subseq = "" end = 0 for ic in range(start, ncols): char = align.rows[ir][ic] if char == "-" or char == "N": continue else: subseq += char if len(subseq) == minSeqLen: end = ic + 1 # forward scores = self.score_seq(subseq) raw, forward_score = scores[0] # reverse scores = self.score_reverse_seq(subseq) raw, reverse_score = scores[0] score = max(forward_score, reverse_score) # replace the alignment positions with the result if byPosition: scoremax[ir][start] = score else: # replace positions matching the width of the pwm for i in range(start, end): if isnan(scoremax[ir][i]): scoremax[ir][i] = score elif score > scoremax[ir][i]: scoremax[ir][i] = score # mask gap characters if gapmask is None: gapmask = score_align_gaps(align) putmask(scoremax, gapmask, float("nan")) return scoremax # seq can be a string, a list of characters, or a quantum sequence (a list # of hashes from symbols to probability) def score_seq(self, seq): if isinstance(seq[0], dict): return self.score_quantum_seq(seq) scores = [] for start in range(len(seq)): if start + len(self) > len(seq): break subseq = seq[start : start + len(self)] raw = 0 try: for i, nt in enumerate(subseq): raw += self.rows[i][nt.upper()] scaled = self.scaled(raw) except KeyError: raw, scaled = float("nan"), float("nan") scores.append((raw, scaled)) return scores def score_quantum_seq(self, seq): scores = [] for start in range(len(seq)): if start + len(self) > len(seq): break subseq = seq[start : start + len(self)] raw = 0 try: for i, nt in enumerate(subseq): numer = sum(subseq[i][nt] * self.probs[i][nt] for nt in subseq[i]) denom = sum(subseq[i][nt] * self.background[nt] for nt in subseq[i]) raw += math.log(numer / denom, 2) scaled = self.scaled(raw) except KeyError: raw, scaled = float("nan"), float("nan") except OverflowError: raw, scaled = float("nan"), float("nan") except ValueError: raw, scaled = float("nan"), float("nan") scores.append((raw, scaled)) return scores def score_reverse_seq(self, seq): revSeq = reverse_complement(seq) scores = self.score_seq(revSeq) scores.reverse() return scores def scaled(self, val): return (val - self.minSum) / (self.maxSum - self.minSum) def pseudocount(self, base=None): def f(count): return math.sqrt(count + 1) if base in self.alphabet: return f(self.matrix_base_counts[base]) elif base is None: return f(self.sites) else: return float("nan") def simple_probability(self, freq, base, i): # p(base,i) = f(base,i) # ---------------------- # sum(f(base,{A,C,G,T})) return float(freq[i][base]) / sum(freq[i][nt] for nt in self.alphabet) def corrected_probability_score(self, freq, base, i): # p(base,i) = f(base,i) + s(base) # -------------------- # N + sum(s(A,C,T,G)) f = float(freq[i][base]) s = self.pseudocount(base) N = self.sites # print >>sys.stderr, "f:%.3f + s:%.3f = %.3f" % (f,s,f + s) # print >>sys.stderr, "-------------------------" # print >>sys.stderr, "N:%d + %d = %d" % (N,self.pseudocount(), N + self.pseudocount()) # print >>sys.stderr, "\t\t %.3f\n" % ((f + s) / (N + self.pseudocount())) assert (f + s) > 0 return (f + s) / (N + self.pseudocount()) def pwm_score(self, base, i, freq, background=None): if background is None: background = self.background p = self.score_correction(freq, base, i) # print >>sys.stderr, p # print >>sys.stderr, "k %d %c" % (i,base),freq[i][base] b = background[base] try: return math.log(p / b, 2) except OverflowError: # print >>sys.stderr,"base=%c, math.log(%.3f / %.3f)" % (base,p,b) # print >>sys.stderr,self.id return float("nan") except ValueError: # print >>sys.stderr,"base=%c, math.log(%.3f / %.3f)" % (base,p,b) # print >>sys.stderr,self.id return float("nan") def parse_weight(self, weightString): fields = weightString.split(".") if len(fields) > 2: raise ValueError w = int(fields[0]) s = 1 if len(fields) == 2: for _ in range(0, len(fields[1])): s *= 10 w = s * w + int(fields[1]) return (w, s) # w = the weight # s = the scale used (a power of 10) def __str__(self): lines = [self.id] headers = ["%s" % nt for nt in self.alphabet] lines.append("P0\t" + "\t".join(headers)) for ix in range(0, len(self.rows)): weights = ["%d" % self.counts[ix][nt] for nt in self.alphabet] # lines.append(("%02d\t" % ix) + "\t".join(weights) + "\t" + self.consensus[ix]) lines.append( ("%02d\t" % ix) + "\t".join(weights) + "\t" + str(sum(self.counts[ix].values())) + "\t" + self.consensus[ix] ) return "\n".join(lines) def __getitem__(self, key): return self.rows[key] def __setitem__(self, key, value): self.rows[key] = value def __len__(self): return len(self.rows) def score_align_gaps(align): # a blank score matrix nrows, ncols = align.dims scoremax = AlignScoreMatrix(align).matrix for ir in range(nrows): # row is missing data if isnan(align.rows[ir][0]): continue # scan for gaps for pos in range(ncols): if align.rows[ir][pos] == "-": scoremax[ir][pos] = 1 else: scoremax[ir][pos] = 0 return scoremax # ----------- # # WeightMatrix Reader-- # Read position weight matrices (PWM) from a file. # # ----------- class Reader: """Iterate over all interesting weight matrices in a file""" def __init__(self, file, tfIds=None, name=None, format="basic", background=None, score_correction=True): self.tfIds = tfIds self.file = file self.name = name self.lineNumber = 0 self.format = format self.background = background self.score_correction = score_correction def close(self): self.file.close() def where(self): if self.name is None: return "line %d" % self.lineNumber else: return "line %d in %s" % (self.lineNumber, self.name) def __iter__(self): if self.format == "basic": return self.read_as_basic() elif self.format == "transfac": return self.read_as_transfac() else: raise ValueError("unknown weight matrix file format: '%s'" % self.format) def read_as_basic(self): tfId = None pwmRows = None alphabet = ["A", "C", "G", "T"] while True: line = self.file.readline() if not line: break line = line.strip() self.lineNumber += 1 if line.startswith(">"): if pwmRows is not None: yield PositionWeightMatrix(tfId, pwmRows, alphabet, background=self.background) # try: # yield PositionWeightMatrix(tfId,pwmRows,alphabet) # except: # print >>sys.stderr, "Failed to read", tfId tfId = line.strip()[1:] pwmRows = [] elif line[0].isdigit(): tokens = line.strip().split() tokens.append(consensus_symbol(line)) # print >>sys.stderr,[ "%.2f" % (float(v)/sum(vals)) for v in vals], tokens[-1] pwmRows.append(tokens) if pwmRows is not None: # we've finished collecting a desired matrix yield PositionWeightMatrix( tfId, pwmRows, alphabet, background=self.background, score_correction=self.score_correction ) def read_as_transfac(self): self.tfToPwm = {} tfId = None pwmRows = None while True: line = self.file.readline() if not line: break line = line.strip() self.lineNumber += 1 # handle an ID line if line.startswith("ID"): if pwmRows is not None: # we've finished collecting a desired matrix try: # FIXME: alphabet is undefined here! yield PositionWeightMatrix( tfId, pwmRows, alphabet, # noqa: F821 background=self.background, score_correction=self.score_correction, ) except Exception: print("Failed to read", tfId, file=sys.stderr) tfId = None pwmRows = None tokens = line.split(None, 2) if len(tokens) != 2: raise ValueError("bad line, need two fields (%s)" % self.where()) tfId = tokens[1] if self.tfIds is not None and (tfId not in self.tfIds): continue # ignore it, this isn't a desired matrix if tfId in self.tfToPwm: raise ValueError(f"transcription factor {tfId} appears twice ({self.where()})") pwmRows = [] # start collecting a desired matrix continue # if we're not collecting, skip this line if pwmRows is None: continue if len(line) < 1: continue # name, if present, added to ID if line.startswith("NA"): words = line.strip().split() tfId = tfId + "\t" + " ".join(words[1:]) # handle a P0 line if line.startswith("P0"): alphabet = line.split()[1:] if len(alphabet) < 2: raise ValueError("bad line, need more dna (%s)" % self.where()) continue # handle a 01,02,etc. line if line[0].isdigit(): tokens = line.split() try: index = int(tokens[0]) if index != len(pwmRows) + 1: raise ValueError except Exception: raise ValueError("bad line, bad index (%s)" % self.where()) pwmRows.append(tokens[1:]) continue # skip low quality entries if line.startswith("CC TRANSFAC Sites of quality"): print(line.strip(), tfId, file=sys.stderr) pwmRows = None continue if pwmRows is not None: # we've finished collecting a desired matrix yield PositionWeightMatrix( tfId, pwmRows, alphabet, background=self.background, score_correction=self.score_correction ) # clean up self.tfToPwm = None def isnan(x): # return ieeespecial.isnan(x) if x == x: return False return True def reverse_complement(nukes): return nukes[::-1].translate(PositionWeightMatrix.complementMap) def rsquared(x, y): try: return sum_of_squares(x, y) ** 2 / (sum_of_squares(x) * sum_of_squares(y)) except ZeroDivisionError: # return float('nan') return 0 def sum_of_squares(x, y=None): if not y: y = x xmean = float(sum(x)) / len(x) ymean = float(sum(y)) / len(y) assert len(x) == len(y) return sum(float(xi) * float(yi) for xi, yi in zip(x, y)) - len(x) * xmean * ymean def consensus_symbol(pattern): if isinstance(pattern, str): try: pattern = [int(x) for x in pattern.split()] except ValueError as e: print(pattern, file=sys.stderr) raise ValueError(e) # IUPAC-IUB nomenclature for wobblers wobblers = { "R": frozenset(["A", "G"]), "Y": frozenset(["C", "T"]), "M": frozenset(["A", "C"]), "K": frozenset(["G", "T"]), "S": frozenset(["G", "C"]), "W": frozenset(["A", "T"]), "H": frozenset(["A", "C", "T"]), "B": frozenset(["G", "T", "C"]), "V": frozenset(["G", "C", "A"]), "D": frozenset(["G", "T", "A"]), } symbols = ["A", "C", "G", "T"] if isinstance(pattern, dict): pattern = [pattern[u] for u in symbols] total = sum(pattern) f = [(space / 1e5) + (float(x) / total) for space, x in enumerate(pattern)] copy = [] copy[:] = f[:] copy.sort() # http://www.genomatix.de/online_help/help_matinspector/matrix_help.html -- # url says consensus must be greater than 50%, and at least twice the freq # of the second-most frequent. A double-degenerate symbol can be used # if the top two account for 75% or more of the nt, if each is less than 50% # Otherwise, N is used in the consensus. tops = copy[-2:] if tops[1] > 0.5 and tops[1] >= 2 * tops[0]: return symbols[f.index(tops[1])] elif tops[0] < 0.5 and sum(tops) >= 0.75: degen = frozenset(symbols[f.index(v)] for v in tops) for degenSymbol, wobbles in wobblers.items(): # print >>sys.stderr,wobbles if degen == wobbles: return degenSymbol else: return "N" print(pattern, file=sys.stderr) raise Exception("?") # import C extensions try: from ._position_weight_matrix import c_match_consensus def match_consensus(sequence, pattern): return c_match_consensus(sequence, pattern, len(sequence)) # print >>sys.stderr, "C match_consensus used" except ImportError: # print >>sys.stderr, "python match_consensus used" def match_consensus(sequence, pattern, size): for s, p in zip(sequence, pattern): if p == "N": continue if s not in PositionWeightMatrix.symbols[p]: return False return True
mit
954ed2f9a6761e52b7c4c51ac5ab2a8f
32.899344
123
0.500065
3.891973
false
false
false
false
bxlab/bx-python
scripts/maf_extract_ranges_indexed.py
1
4636
#!/usr/bin/env python """ Reads a list of intervals and a maf. Produces a new maf containing the blocks or parts of blocks in the original that overlapped the intervals. It is assumed that each file `maf_fname` has a corresponding `maf_fname`.index file. NOTE: If two intervals overlap the same block it will be written twice. With non-overlapping intervals and --chop this is never a problem. NOTE: Intervals are origin-zero, half-open. For example, the interval 100,150 is 50 bases long, and there are 100 bases to its left in the sequence. NOTE: Intervals are relative to the + strand, regardless of the strands in the alignments. WARNING: bz2/bz2t support and file cache support are new and not as well tested. usage: %prog maf_fname1 maf_fname2 ... [options] < interval_file -m, --mincols=0: Minimum length (columns) required for alignment to be output -c, --chop: Should blocks be chopped to only portion overlapping (no by default) -s, --src=s: Use this src for all intervals -p, --prefix=p: Prepend this to each src before lookup -d, --dir=d: Write each interval as a separate file in this directory -S, --strand: Strand is included as an additional column, and the blocks are reverse complemented (if necessary) so that they are always on that strand w/r/t the src species. -C, --usecache: Use a cache that keeps blocks of the MAF files in memory (requires ~20MB per MAF) """ import os import sys import bx.align.maf from bx.cookbook import doc_optparse def main(): # Parse Command Line options, args = doc_optparse.parse(__doc__) try: maf_files = args if options.mincols: mincols = int(options.mincols) else: mincols = 0 if options.src: fixed_src = options.src else: fixed_src = None if options.prefix: prefix = options.prefix else: prefix = None if options.dir: dir = options.dir else: dir = None chop = bool(options.chop) do_strand = bool(options.strand) use_cache = bool(options.usecache) except Exception: doc_optparse.exit() # Open indexed access to mafs index = bx.align.maf.MultiIndexed(maf_files, keep_open=True, parse_e_rows=True, use_cache=use_cache) # Start MAF on stdout if dir is None: out = bx.align.maf.Writer(sys.stdout) # Iterate over input ranges for line in sys.stdin: strand = None fields = line.split() if fixed_src: src, start, end = fixed_src, int(fields[0]), int(fields[1]) if do_strand: strand = fields[2] else: src, start, end = fields[0], int(fields[1]), int(fields[2]) if do_strand: strand = fields[3] if prefix: src = prefix + src # Find overlap with reference component blocks = index.get(src, start, end) # Open file if needed if dir: out = bx.align.maf.Writer(open(os.path.join(dir, "%s:%09d-%09d.maf" % (src, start, end)), "w")) # Write each intersecting block if chop: for block in blocks: for ref in block.get_components_by_src(src): slice_start = max(start, ref.get_forward_strand_start()) slice_end = min(end, ref.get_forward_strand_end()) if slice_end <= slice_start: continue sliced = block.slice_by_component(ref, slice_start, slice_end) # If the block is shorter than the minimum allowed size, stop if mincols and (sliced.text_size < mincols): continue # If the reference component is empty, don't write the block if sliced.get_component_by_src(src).size < 1: continue # Keep only components that are not empty sliced.components = [c for c in sliced.components if c.size > 0 or c.empty] # Reverse complement if needed if strand is not None and ref.strand != strand: sliced = sliced.reverse_complement() # Write the block out.write(sliced) else: for block in blocks: out.write(block) if dir: out.close() # Close output MAF out.close() index.close() if __name__ == "__main__": main()
mit
b23785af7a06b66ac295d24c974f20c3
36.691057
181
0.580026
3.945532
false
false
false
false
bxlab/bx-python
lib/bx/intervals/operations/find_clusters.py
1
5191
""" Find clusters of intervals within a set of intervals. A cluster is a group (of size minregions) of intervals within a specific distance (of mincols) of each other. Returns Cluster objects, which have a chrom, start, end, and lines (a list of linenumbers from the original file). The original can then be ran through with the linenumbers to extract clustered regions without disturbing original order, or the clusters may themselves be written as intervals. """ import math import random from bx.intervals.cluster import ClusterTree from bx.intervals.io import GenomicInterval def find_clusters(reader, mincols=1, minregions=2): extra = dict() chroms = dict() linenum = -1 for interval in reader: linenum += 1 if not isinstance(interval, GenomicInterval): extra[linenum] = interval else: if interval.chrom not in chroms: chroms[interval.chrom] = ClusterTree(mincols, minregions) try: chroms[interval.chrom].insert(interval.start, interval.end, linenum) except OverflowError as e: try: # This will work only if reader is a NiceReaderWrapper reader.skipped += 1 if reader.skipped < 10: reader.skipped_lines.append((reader.linenum, reader.current_line, str(e))) except Exception: pass continue return chroms, extra # DEPRECATED: Use the ClusterTree in bx.intervals.cluster for this. # It does the same thing, but is a C implementation. class ClusterNode: def __init__(self, start, end, linenum, mincols, minregions): # Python lacks the binomial distribution, so we convert a # uniform into a binomial because it naturally scales with # tree size. Also, python's uniform is perfect since the # upper limit is not inclusive, which gives us undefined here. self.priority = math.ceil((-1.0 / math.log(0.5)) * math.log(-1.0 / (random.uniform(0, 1) - 1))) self.start = start self.end = end self.left = None self.right = None self.lines = [linenum] self.mincols = mincols self.minregions = minregions def insert(self, start, end, linenum): if start - self.mincols > self.end: # insert to right tree if self.right: self.right = self.right.insert(start, end, linenum) else: self.right = ClusterNode(start, end, linenum, self.mincols, self.minregions) # rebalance tree if self.priority < self.right.priority: return self.rotateleft() elif end + self.mincols < self.start: # insert to left tree if self.left: self.left = self.left.insert(start, end, linenum) else: self.left = ClusterNode(start, end, linenum, self.mincols, self.minregions) # rebalance tree if self.priority < self.left.priority: return self.rotateright() else: # insert here self.start = min(self.start, start) self.end = max(self.end, end) self.lines.append(linenum) # recursive call to push nodes up if self.left: self.left = self.left.push_up(self) if self.right: self.right = self.right.push_up(self) return self def rotateright(self): root = self.left self.left = self.left.right root.right = self return root def rotateleft(self): root = self.right self.right = self.right.left root.left = self return root def push_up(self, topnode): # Note: this function does not affect heap property # Distance method removed for inline, faster? distance = max(self.start, topnode.start) - min(self.end, topnode.end) if distance <= self.mincols: topnode.start = min(self.start, topnode.start) topnode.end = max(self.end, topnode.end) for linenum in self.lines: topnode.lines.append(linenum) if self.right: return self.right.push_up(topnode) if self.left: return self.left.push_up(topnode) return None if self.end < topnode.start and self.right: self.right = self.right.push_up(topnode) if self.start > topnode.end and self.left: self.left = self.left.push_up(topnode) return self def getintervals(self): if self.left: yield from self.left.getintervals(self.minregions) if len(self.lines) >= self.minregions: yield self.start, self.end if self.right: yield from self.right.getintervals(self.minregions) def getlines(self): if self.left: yield from self.left.getlines() if len(self.lines) >= self.minregions: yield from self.lines if self.right: yield from self.right.getlines()
mit
35ce38c78a2f20d34d78e2f7672d676a
36.345324
103
0.592564
4.146166
false
false
false
false
myint/rstcheck
prep_release.py
1
7175
"""Script for preparing the repo for a new release.""" import argparse import re import subprocess # noqa: S404 import sys from datetime import date if sys.version_info[0:2] <= (3, 6): raise RuntimeError("Script runs only with python 3.7 or newer.") PATCH = ("patch", "bugfix") MINOR = ("minor", "feature") MAJOR = ("major", "breaking") REPO_URL = "https://github.com/myint/rstcheck" #: -- UTILS ---------------------------------------------------------------------------- class PyprojectError(Exception): """Exception for lookup errors in pyproject.toml file.""" def _get_config_value(section: str, key: str) -> str: # noqa: CCR001 """Extract a config value from pyproject.toml file. :return: config value """ with open("pyproject.toml", encoding="utf8") as pyproject_file: pyproject = pyproject_file.read().split("\n") start = False for line in pyproject: if not start and line.strip().startswith(section): start = True continue if start and line.strip().startswith("["): break if start and line.strip().startswith(key): match = re.match(r"\s*" + key + r"""\s?=\s?["']{1}([^"']*)["']{1}.*""", line) if match: return match.group(1) raise PyprojectError( f"No value for key '{key}' in {section} section could be extracted." ) raise PyprojectError(f"No '{key}' found in {section} section.") def _set_config_value(section: str, key: str, value: str) -> None: """Set a config value in pyproject.toml file.""" with open("pyproject.toml", encoding="utf8") as pyproject_file: pyproject = pyproject_file.read().split("\n") start = False for idx, line in enumerate(pyproject): if not start and line.strip().startswith(section): start = True continue if start and line.strip().startswith("["): raise PyprojectError(f"No '{key}' found in {section} section.") if start and line.strip().startswith(key): match = re.sub( r"(\s*" + key + r"""\s?=\s?["']{1})[^"']*(["']{1}.*)""", f"\\g<1>{value}\\g<2>", line, ) pyproject[idx] = match break with open("pyproject.toml", "w", encoding="utf8") as pyproject_file: pyproject_file.write("\n".join(pyproject)) #: -- MAIN ----------------------------------------------------------------------------- def bump_version(release_type: str = "patch") -> str: """Bump the current version for the next release. :param release_type: type of release; allowed values are: patch | minor/feature | major/breaking; defaults to "patch" :raises ValueError: when an invalid release_type is given. :raises ValueError: when the version string from pyproject.toml is not parsable. :return: new version string """ if release_type not in PATCH + MINOR + MAJOR: raise ValueError(f"Invalid version increase type: {release_type}") current_version = _get_config_value("[tool.poetry]", "version") version_parts = re.match(r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)", current_version) if not version_parts: raise ValueError(f"Unparsable version: {current_version}") if release_type in MAJOR: version = f"{int(version_parts.group('major')) + 1}.0.0" elif release_type in MINOR: version = f"{version_parts.group('major')}" f".{int(version_parts.group('minor')) + 1}.0" elif release_type in PATCH: version = ( f"{version_parts.group('major')}" f".{version_parts.group('minor')}" f".{int(version_parts.group('patch')) + 1}" ) else: print("Given `RELEASE TYPE` is invalid.") sys.exit(1) _set_config_value("[tool.poetry]", "version", version) return version def update_changelog(new_version: str, last_version: str, first_release: bool) -> None: """Update CHANGELOG.md to be release ready. :param new_version: new version string :param last_version: current version string :first_release: if this is the first release """ with open("CHANGELOG.md", encoding="utf8") as changelog_file: changelog_lines = changelog_file.read().split("\n") release_line = 0 for idx, line in enumerate(changelog_lines): if line.startswith("## Unreleased"): release_line = idx if release_line: today = date.today().isoformat() compare = f"{'' if first_release else 'v'}{last_version}...v{new_version}" changelog_lines[release_line] = ( "## Unreleased\n" "\n" f"[diff v{new_version}...master]" f"({REPO_URL}/compare/v{new_version}...main)\n" "\n" f"## [{new_version}]({REPO_URL}/releases/v{new_version}) ({today})\n" f"[diff {compare}]({REPO_URL}/compare/{compare})" ) #: Remove [diff ...] link line if len(changelog_lines) - 1 >= release_line + 1: changelog_lines.pop(release_line + 1) with open("CHANGELOG.md", "w", encoding="utf8") as changelog_file: changelog_file.write("\n".join(changelog_lines)) def commit_and_tag(version: str) -> None: """Git commit and tag the new release.""" subprocess.run( # noqa: S603,S607 [ "git", "commit", "--no-verify", f"--message=release v{version} [skip ci]", "--include", "pyproject.toml", "CHANGELOG.md", ], check=True, ) subprocess.run( # noqa: S603,S607 ["git", "tag", "-am", f"'v{version}'", f"v{version}"], check=True ) def _parser() -> argparse.Namespace: """Create parser and return parsed args.""" parser = argparse.ArgumentParser() parser.add_argument( "increase_type", metavar="RELEASE TYPE", default="patch", nargs="?", help=( "Release type: patch/bugfix | minor/feature | major/breaking; " "gets ignored on `--first-release`; " "defaults to patch" ), ) parser.add_argument( "--first-release", action="store_true", help="Flag for first release to prevent version bumping.", ) return parser.parse_args() def _main() -> int: """Prepare release main routine.""" args = _parser() if args.first_release: release_version = _get_config_value("[tool.poetry]", "version") #: Get first commit current_version = subprocess.run( # noqa: S603,S607 ["git", "rev-list", "--max-parents=0", "HEAD"], check=True, capture_output=True, ).stdout.decode()[0:7] else: current_version = _get_config_value("[tool.poetry]", "version") release_version = bump_version(args.increase_type) update_changelog( release_version, current_version, args.first_release, ) commit_and_tag(release_version) return 0 if __name__ == "__main__": sys.exit(_main())
mit
0b02681b6ee5042ecf978811c759305e
31.466063
97
0.560279
3.746736
false
false
false
false
myint/rstcheck
tests/test_runner.py
1
15529
"""Tests for ``runner`` module.""" # pylint: disable=protected-access import contextlib import multiprocessing import pathlib import sys import typing as t import pytest import pytest_mock from rstcheck import checker, config, runner, types from tests.conftest import EXAMPLES_DIR class TestRstcheckMainRunnerInit: """Test ``RstcheckMainRunner.__init__`` method.""" @staticmethod def test_load_config_file_if_set(mocker: pytest_mock.MockerFixture) -> None: """Test config file is loaded if set.""" mocked_loader = mocker.patch.object(runner.RstcheckMainRunner, "load_config_file") config_file_path = pathlib.Path("some-file") init_config = config.RstcheckConfig(config_path=config_file_path) runner.RstcheckMainRunner([], init_config) # act mocked_loader.assert_called_once_with(config_file_path, False) @staticmethod def test_no_load_config_file_if_unset(mocker: pytest_mock.MockerFixture) -> None: """Test no config file is loaded if unset.""" mocked_loader = mocker.patch.object(runner.RstcheckMainRunner, "load_config_file") init_config = config.RstcheckConfig() runner.RstcheckMainRunner([], init_config) # act mocked_loader.assert_not_called() @staticmethod @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific.") @pytest.mark.parametrize("pool_size", [0, 1, 60, 61, 62, 100]) def test_max_pool_size_on_windows(pool_size: int, monkeypatch: pytest.MonkeyPatch) -> None: """Test pool size is 61 at max on windows.""" monkeypatch.setattr(multiprocessing, "cpu_count", lambda: pool_size) init_config = config.RstcheckConfig() result = runner.RstcheckMainRunner([], init_config)._pool_size assert result <= 61 class TestRstcheckMainRunnerConfigFileLoader: """Test ``RstcheckMainRunner.load_config_file`` method.""" @staticmethod def test_no_config_update_on_no_file_config(monkeypatch: pytest.MonkeyPatch) -> None: """Test config is not updated when no file config is found.""" monkeypatch.setattr( config, "load_config_file_from_path", lambda _, warn_unknown_settings: None ) init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner.load_config_file(pathlib.Path()) # act assert _runner.config == init_config @staticmethod def test_config_update_on_found_file_config(monkeypatch: pytest.MonkeyPatch) -> None: """Test config is updated when file config is found.""" file_config = config.RstcheckConfigFile(report_level=config.ReportLevel.SEVERE) monkeypatch.setattr( config, "load_config_file_from_path", lambda _, warn_unknown_settings: file_config ) init_config = config.RstcheckConfig(report_level=config.ReportLevel.INFO) _runner = runner.RstcheckMainRunner([], init_config, overwrite_config=True) _runner.load_config_file(pathlib.Path()) # act assert _runner.config.report_level == config.ReportLevel.SEVERE class TestRstcheckMainRunnerFileListUpdater: """Test ``RstcheckMainRunner.update_file_list`` method.""" @staticmethod def test_empty_file_list() -> None: """Test empty file list results in no changes.""" file_list: t.List[pathlib.Path] = [] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert not _runner.files_to_check @staticmethod def test_single_file_in_list() -> None: """Test single file in list results in only this file in the list.""" file_list = [EXAMPLES_DIR / "good" / "rst.rst"] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert _runner.files_to_check == file_list @staticmethod def test_multiple_files_in_list() -> None: """Test multiple files in list results in only these files in the list.""" file_list = [ EXAMPLES_DIR / "good" / "rst.rst", EXAMPLES_DIR / "bad" / "rst.rst", ] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert _runner.files_to_check == file_list @staticmethod def test_non_rst_files() -> None: """Test non rst files are filtered out.""" file_list = [ EXAMPLES_DIR / "good" / "rst.rst", EXAMPLES_DIR / "good" / "foo.h", EXAMPLES_DIR / "bad" / "rst.rst", ] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert len(_runner.files_to_check) == 2 @staticmethod def test_directory_without_recursive() -> None: """Test directory without recusrive results in empty file list.""" file_list = [EXAMPLES_DIR / "good"] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert not _runner.files_to_check @staticmethod def test_directory_with_recursive() -> None: """Test directory with recusrive results in directories files in file list.""" file_list = [EXAMPLES_DIR / "good"] init_config = config.RstcheckConfig(recursive=True) _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert len(_runner.files_to_check) == 6 assert EXAMPLES_DIR / "good" / "rst.rst" in _runner.files_to_check @staticmethod def test_dash_as_file() -> None: """Test dash as file.""" file_list = [pathlib.Path("-")] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert file_list == _runner.files_to_check @staticmethod def test_dash_as_file_with_others() -> None: """Test dash as file with other files gets ignored.""" file_list = [pathlib.Path("-"), EXAMPLES_DIR / "good" / "rst.rst"] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) _runner.update_file_list() # act assert len(_runner.files_to_check) == 1 assert EXAMPLES_DIR / "good" / "rst.rst" in _runner.files_to_check @pytest.mark.parametrize( "lint_errors", [[], [types.LintError(source_origin="<string>", line_number=0, message="message")]], ) def test__run_checks_sync_method( lint_errors: t.List[types.LintError], monkeypatch: pytest.MonkeyPatch ) -> None: """Test ``RstcheckMainRunner._run_checks_sync`` method. Test results are returned. """ monkeypatch.setattr(checker, "check_file", lambda _0, _1, _2: lint_errors) file_list = [ EXAMPLES_DIR / "good" / "rst.rst", EXAMPLES_DIR / "bad" / "rst.rst", ] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) result = _runner._run_checks_sync() assert len(result) == 2 assert len(result[0]) == len(lint_errors) assert len(result[1]) == len(lint_errors) @pytest.mark.parametrize( "lint_errors", [[], [types.LintError(source_origin="<string>", line_number=0, message="message")]], ) def test__run_checks_parallel_method( lint_errors: t.List[types.LintError], monkeypatch: pytest.MonkeyPatch ) -> None: # noqa: AAA05 """Test ``RstcheckMainRunner._run_checks_parallel`` method. Test results are returned. The multiprocessing.Pool needs to be mocked, because it interferes with pytest-xdist. """ class MockedPool: # pylint: disable=too-few-public-methods """Mocked instance of ``multiprocessing.Pool``.""" # noqa: AAA05 @staticmethod def starmap(_0, _1) -> t.List[t.List[types.LintError]]: # noqa: ANN001 """Mock for ``multiprocessing.Pool.starmap`` method.""" return [lint_errors, lint_errors] # noqa: AAA05 @contextlib.contextmanager def mock_pool(_) -> t.Generator[MockedPool, None, None]: # noqa: ANN001 """Mock context manager for ``multiprocessing.Pool``.""" yield MockedPool() # noqa: AAA05 monkeypatch.setattr(multiprocessing, "Pool", mock_pool) file_list = [ EXAMPLES_DIR / "good" / "rst.rst", EXAMPLES_DIR / "bad" / "rst.rst", ] init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner(file_list, init_config) result = _runner._run_checks_parallel() # act assert len(result) == 2 assert len(result[0]) == len(lint_errors) assert len(result[1]) == len(lint_errors) @pytest.mark.parametrize( ("results", "error_count"), [([], 0), ([[types.LintError(source_origin="<string>", line_number=0, message="message")]], 1)], ) def test__update_results_method(results: t.List[t.List[types.LintError]], error_count: int) -> None: """Test ``RstcheckMainRunner._update_results`` method. Test results are set. """ init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner._update_results(results) # act assert len(_runner.errors) == error_count def test_check_method_sync_with_1_file(mocker: pytest_mock.MockerFixture) -> None: """Test ``RstcheckMainRunner.check`` method. Test checks are run in sync for 1 file. """ mocked_sync_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_sync") mocked_parallel_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_parallel") init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner.files_to_check = [pathlib.Path("file")] _runner.check() # act mocked_sync_runner.assert_called_once() mocked_parallel_runner.assert_not_called() def test_check_method_parallel_with_more_files(mocker: pytest_mock.MockerFixture) -> None: """Test ``RstcheckMainRunner.check`` method. Test checks are run in parallel for more file. """ mocked_sync_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_sync") mocked_parallel_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_parallel") init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner.files_to_check = [pathlib.Path("file"), pathlib.Path("file2")] _runner.check() # act mocked_sync_runner.assert_not_called() mocked_parallel_runner.assert_called_once() class TestRstcheckMainRunnerResultPrinter: """Test ``RstcheckMainRunner.get_result`` method.""" @staticmethod def test_exit_code_on_success() -> None: """Test exit code 0 is returned on no erros.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) result = _runner.print_result() assert result == 0 @staticmethod def test_success_message_on_success(capsys: pytest.CaptureFixture[str]) -> None: """Test success message is printed to stdout by default if no errors.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner.print_result() # act assert "Success! No issues detected." in capsys.readouterr().out @staticmethod def test_success_message_print_to_file(tmp_path: pathlib.Path) -> None: """Test success message is printed to given file.""" out_file = tmp_path / "outfile.txt" out_file.touch() init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) with open(out_file, encoding="utf-8", mode="w") as out_file_handle: _runner.print_result(output_file=out_file_handle) # act assert "Success! No issues detected." in out_file.read_text() @staticmethod def test_exit_code_on_error() -> None: """Test exit code 1 is returned when erros were found.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner.errors = [ types.LintError(source_origin="<string>", line_number=0, message="message") ] result = _runner.print_result() assert result == 1 @staticmethod def test_no_success_message_on_error(capsys: pytest.CaptureFixture[str]) -> None: """Test no succuess message is printed when erros were found.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner.errors = [ types.LintError(source_origin="<string>", line_number=0, message="message") ] _runner.print_result() # act assert "Success! No issues detected." not in capsys.readouterr() @staticmethod def test_error_printed_to_stderr_by_default(capsys: pytest.CaptureFixture[str]) -> None: """Test errors are printed to stderr.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner._update_results( [[types.LintError(source_origin="<string>", line_number=0, message="Some error.")]] ) _runner.print_result() # act assert "(ERROR/3) Some error" in capsys.readouterr().err @staticmethod def test_error_printed_to_file(tmp_path: pathlib.Path) -> None: """Test errors are printed to stderr.""" out_file = tmp_path / "outfile.txt" out_file.touch() init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner._update_results( [[types.LintError(source_origin="<string>", line_number=0, message="Some error.")]] ) with open(out_file, encoding="utf-8", mode="w") as out_file_handle: _runner.print_result(output_file=out_file_handle) # act assert "(ERROR/3) Some error" in out_file.read_text() @staticmethod def test_error_category_prepend(capsys: pytest.CaptureFixture[str]) -> None: """Test ``(ERROR/3)`` is prepended when no category is present.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner._update_results( [[types.LintError(source_origin="<string>", line_number=0, message="Some error.")]] ) _runner.print_result() # act assert "(ERROR/3) Some error." in capsys.readouterr().err @staticmethod def test_error_message_format(capsys: pytest.CaptureFixture[str]) -> None: """Test error message format.""" init_config = config.RstcheckConfig() _runner = runner.RstcheckMainRunner([], init_config) _runner._update_results( [ [ types.LintError( source_origin="<string>", line_number=0, message="(ERROR/3) Some error." ) ] ] ) _runner.print_result() # act assert "<string>:0: (ERROR/3) Some error." in capsys.readouterr().err
mit
5317c03ac686e4132c4958c610fdeddc
35.367681
100
0.637903
3.64445
false
true
false
false
michael-lazar/rtv
scripts/update_packages.py
1
1382
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update the project's bundled dependencies by downloading the git repository and copying over the most recent commit. """ import os import shutil import subprocess import tempfile _filepath = os.path.dirname(os.path.relpath(__file__)) ROOT = os.path.abspath(os.path.join(_filepath, '..')) PRAW_REPO = 'https://github.com/michael-lazar/praw3.git' def main(): tmpdir = tempfile.mkdtemp() subprocess.check_call(['git', 'clone', PRAW_REPO, tmpdir]) # Update the commit hash reference os.chdir(tmpdir) p = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE) p.wait() commit = p.stdout.read().strip() print('Found commit %s' % commit) regex = 's/^__praw_hash__ =.*$/__praw_hash__ = \'%s\'/g' % commit packages_root = os.path.join(ROOT, 'rtv', 'packages', '__init__.py') print('Updating commit hash in %s' % packages_root) subprocess.check_call(['sed', '-i', '', regex, packages_root]) # Overwrite the project files src = os.path.join(tmpdir, 'praw') dest = os.path.join(ROOT, 'rtv', 'packages', 'praw') print('Copying package files to %s' % dest) shutil.rmtree(dest, ignore_errors=True) shutil.copytree(src, dest) # Cleanup print('Removing directory %s' % tmpdir) shutil.rmtree(tmpdir) if __name__ == '__main__': main()
mit
63cd97218de18c75e8cbe8ff839f0577
27.204082
79
0.638205
3.28266
false
false
false
false
michael-lazar/rtv
rtv/page.py
1
31508
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import os import sys import time import logging from functools import wraps import six from kitchen.text.display import textual_width from . import docs from .clipboard import copy as clipboard_copy from .objects import Controller, Command from .exceptions import TemporaryFileError, ProgramError from .__version__ import __version__ _logger = logging.getLogger(__name__) def logged_in(f): """ Decorator for Page methods that require the user to be authenticated. """ @wraps(f) def wrapped_method(self, *args, **kwargs): if not self.reddit.is_oauth_session(): self.term.show_notification('Not logged in') return None return f(self, *args, **kwargs) return wrapped_method class PageController(Controller): character_map = {} class Page(object): BANNER = None FOOTER = None def __init__(self, reddit, term, config, oauth): self.reddit = reddit self.term = term self.config = config self.oauth = oauth self.content = None self.nav = None self.controller = None self.active = True self.selected_page = None self._row = 0 self._subwindows = None def refresh_content(self, order=None, name=None): raise NotImplementedError def _draw_item(self, win, data, inverted): raise NotImplementedError def get_selected_item(self): """ Return the content dictionary that is currently selected by the cursor. """ return self.content.get(self.nav.absolute_index) def loop(self): """ Main control loop runs the following steps: 1. Re-draw the screen 2. Wait for user to press a key (includes terminal resizing) 3. Trigger the method registered to the input key 4. Check if there are any nested pages that need to be looped over The loop will run until self.active is set to False from within one of the methods. """ self.active = True # This needs to be called once before the main loop, in case a subpage # was pre-selected before the loop started. This happens in __main__.py # with ``page.open_submission(url=url)`` while self.selected_page and self.active: self.handle_selected_page() while self.active: self.draw() ch = self.term.stdscr.getch() self.controller.trigger(ch) while self.selected_page and self.active: self.handle_selected_page() return self.selected_page def handle_selected_page(self): """ Some commands will result in an action that causes a new page to open. Examples include selecting a submission, viewing subscribed subreddits, or opening the user's inbox. With these commands, the newly selected page will be pre-loaded and stored in ``self.selected_page`` variable. It's up to each page type to determine what to do when another page is selected. - It can start a nested page.loop(). This would allow the user to return to their previous screen after exiting the sub-page. For example, this is what happens when opening an individual submission from within a subreddit page. When the submission is closed, the user resumes the subreddit that they were previously viewing. - It can close the current self.loop() and bubble the selected page up one level in the loop stack. For example, this is what happens when the user opens their subscriptions and selects a subreddit. The subscription page loop is closed and the selected subreddit is bubbled up to the root level loop. Care should be taken to ensure the user can never enter an infinite nested loop, as this could lead to memory leaks and recursion errors. # Example of an unsafe nested loop subreddit_page.loop() -> submission_page.loop() -> subreddit_page.loop() -> submission_page.loop() ... """ raise NotImplementedError @PageController.register(Command('REFRESH')) def reload_page(self): """ Clear the PRAW cache to force the page the re-fetch content from reddit. """ self.reddit.handler.clear_cache() self.refresh_content() @PageController.register(Command('EXIT')) def exit(self): """ Prompt and exit the application. """ if self.term.prompt_y_or_n('Do you really want to quit? (y/n): '): sys.exit() @PageController.register(Command('FORCE_EXIT')) def force_exit(self): """ Immediately exit the application. """ sys.exit() @PageController.register(Command('PREVIOUS_THEME')) def previous_theme(self): """ Cycle to preview the previous theme from the internal list of themes. """ theme = self.term.theme_list.previous(self.term.theme) while not self.term.check_theme(theme): theme = self.term.theme_list.previous(theme) self.term.set_theme(theme) self.draw() message = self.term.theme.display_string self.term.show_notification(message, timeout=1) @PageController.register(Command('NEXT_THEME')) def next_theme(self): """ Cycle to preview the next theme from the internal list of themes. """ theme = self.term.theme_list.next(self.term.theme) while not self.term.check_theme(theme): theme = self.term.theme_list.next(theme) self.term.set_theme(theme) self.draw() message = self.term.theme.display_string self.term.show_notification(message, timeout=1) @PageController.register(Command('HELP')) def show_help(self): """ Open the help documentation in the system pager. """ self.term.open_pager(docs.HELP.strip()) @PageController.register(Command('MOVE_UP')) def move_cursor_up(self): """ Move the cursor up one selection. """ self._move_cursor(-1) self.clear_input_queue() @PageController.register(Command('MOVE_DOWN')) def move_cursor_down(self): """ Move the cursor down one selection. """ self._move_cursor(1) self.clear_input_queue() @PageController.register(Command('PAGE_UP')) def move_page_up(self): """ Move the cursor up approximately the number of entries on the page. """ self._move_page(-1) self.clear_input_queue() @PageController.register(Command('PAGE_DOWN')) def move_page_down(self): """ Move the cursor down approximately the number of entries on the page. """ self._move_page(1) self.clear_input_queue() @PageController.register(Command('PAGE_TOP')) def move_page_top(self): """ Move the cursor to the first item on the page. """ self.nav.page_index = self.content.range[0] self.nav.cursor_index = 0 self.nav.inverted = False @PageController.register(Command('PAGE_BOTTOM')) def move_page_bottom(self): """ Move the cursor to the last item on the page. """ self.nav.page_index = self.content.range[1] self.nav.cursor_index = 0 self.nav.inverted = True @PageController.register(Command('UPVOTE')) @logged_in def upvote(self): """ Upvote the currently selected item. """ data = self.get_selected_item() if 'likes' not in data: self.term.flash() elif getattr(data['object'], 'archived'): self.term.show_notification("Voting disabled for archived post", style='Error') elif data['likes']: with self.term.loader('Clearing vote'): data['object'].clear_vote() if not self.term.loader.exception: data['likes'] = None else: with self.term.loader('Voting'): data['object'].upvote() if not self.term.loader.exception: data['likes'] = True @PageController.register(Command('DOWNVOTE')) @logged_in def downvote(self): """ Downvote the currently selected item. """ data = self.get_selected_item() if 'likes' not in data: self.term.flash() elif getattr(data['object'], 'archived'): self.term.show_notification("Voting disabled for archived post", style='Error') elif data['likes'] or data['likes'] is None: with self.term.loader('Voting'): data['object'].downvote() if not self.term.loader.exception: data['likes'] = False else: with self.term.loader('Clearing vote'): data['object'].clear_vote() if not self.term.loader.exception: data['likes'] = None @PageController.register(Command('SAVE')) @logged_in def save(self): """ Mark the currently selected item as saved through the reddit API. """ data = self.get_selected_item() if 'saved' not in data: self.term.flash() elif not data['saved']: with self.term.loader('Saving'): data['object'].save() if not self.term.loader.exception: data['saved'] = True else: with self.term.loader('Unsaving'): data['object'].unsave() if not self.term.loader.exception: data['saved'] = False @PageController.register(Command('LOGIN')) def login(self): """ Prompt to log into the user's account, or log out of the current account. """ if self.reddit.is_oauth_session(): ch = self.term.show_notification('Log out? (y/n)') if ch in (ord('y'), ord('Y')): self.oauth.clear_oauth_data() self.term.show_notification('Logged out') else: self.oauth.authorize() def reply(self): """ Reply to the selected item. This is a utility method and should not be bound to a key directly. Item type: Submission - add a top level comment Comment - add a comment reply Message - reply to a private message """ data = self.get_selected_item() if data['type'] == 'Submission': body = data['text'] description = 'submission' reply = data['object'].add_comment elif data['type'] in ('Comment', 'InboxComment'): body = data['body'] description = 'comment' reply = data['object'].reply elif data['type'] == 'Message': body = data['body'] description = 'private message' reply = data['object'].reply else: self.term.flash() return # Construct the text that will be displayed in the editor file. # The post body will be commented out and added for reference lines = [' |' + line for line in body.split('\n')] content = '\n'.join(lines) comment_info = docs.REPLY_FILE.format( author=data['author'], type=description, content=content) with self.term.open_editor(comment_info) as comment: if not comment: self.term.show_notification('Canceled') return with self.term.loader('Posting {}'.format(description), delay=0): reply(comment) # Give reddit time to process the submission time.sleep(2.0) if self.term.loader.exception is None: self.reload_page() else: raise TemporaryFileError() @PageController.register(Command('DELETE')) @logged_in def delete_item(self): """ Delete a submission or comment. """ data = self.get_selected_item() if data.get('author') != self.reddit.user.name: self.term.flash() return prompt = 'Are you sure you want to delete this? (y/n): ' if not self.term.prompt_y_or_n(prompt): self.term.show_notification('Canceled') return with self.term.loader('Deleting', delay=0): data['object'].delete() # Give reddit time to process the request time.sleep(2.0) if self.term.loader.exception is None: self.reload_page() @PageController.register(Command('EDIT')) @logged_in def edit(self): """ Edit a submission or comment. """ data = self.get_selected_item() if data.get('author') != self.reddit.user.name: self.term.flash() return if data['type'] == 'Submission': content = data['text'] info = docs.SUBMISSION_EDIT_FILE.format( content=content, id=data['object'].id) elif data['type'] == 'Comment': content = data['body'] info = docs.COMMENT_EDIT_FILE.format( content=content, id=data['object'].id) else: self.term.flash() return with self.term.open_editor(info) as text: if not text or text == content: self.term.show_notification('Canceled') return with self.term.loader('Editing', delay=0): data['object'].edit(text) time.sleep(2.0) if self.term.loader.exception is None: self.reload_page() else: raise TemporaryFileError() @PageController.register(Command('PRIVATE_MESSAGE')) @logged_in def send_private_message(self): """ Send a new private message to another user. """ message_info = docs.MESSAGE_FILE with self.term.open_editor(message_info) as text: if not text: self.term.show_notification('Canceled') return parts = text.split('\n', 2) if len(parts) == 1: self.term.show_notification('Missing message subject') return elif len(parts) == 2: self.term.show_notification('Missing message body') return recipient, subject, message = parts recipient = recipient.strip() subject = subject.strip() message = message.rstrip() if not recipient: self.term.show_notification('Missing recipient') return elif not subject: self.term.show_notification('Missing message subject') return elif not message: self.term.show_notification('Missing message body') return with self.term.loader('Sending message', delay=0): self.reddit.send_message( recipient, subject, message, raise_captcha_exception=True) # Give reddit time to process the message time.sleep(2.0) if self.term.loader.exception: raise TemporaryFileError() else: self.term.show_notification('Message sent!') self.selected_page = self.open_inbox_page('sent') def prompt_and_select_link(self): """ Prompt the user to select a link from a list to open. Return the link that was selected, or ``None`` if no link was selected. """ data = self.get_selected_item() url_full = data.get('url_full') permalink = data.get('permalink') if url_full and url_full != permalink: # The item is a link-only submission that won't contain text link = url_full else: html = data.get('html') if html: extracted_links = self.content.extract_links(html) if not extracted_links: # Only one selection to choose from, so just pick it link = permalink else: # Let the user decide which link to open links = [] if permalink: links += [{'text': 'Permalink', 'href': permalink}] links += extracted_links link = self.term.prompt_user_to_select_link(links) else: # Some items like hidden comments don't have any HTML to parse link = permalink return link @PageController.register(Command('COPY_PERMALINK')) def copy_permalink(self): """ Copy the submission permalink to OS clipboard """ url = self.get_selected_item().get('permalink') self.copy_to_clipboard(url) @PageController.register(Command('COPY_URL')) def copy_url(self): """ Copy a link to OS clipboard """ url = self.prompt_and_select_link() self.copy_to_clipboard(url) def copy_to_clipboard(self, url): """ Attempt to copy the selected URL to the user's clipboard """ if url is None: self.term.flash() return try: clipboard_copy(url) except (ProgramError, OSError) as e: _logger.exception(e) self.term.show_notification( 'Failed to copy url: {0}'.format(e)) else: self.term.show_notification( ['Copied to clipboard:', url], timeout=1) @PageController.register(Command('SUBSCRIPTIONS')) @logged_in def subscriptions(self): """ View a list of the user's subscribed subreddits """ self.selected_page = self.open_subscription_page('subreddit') @PageController.register(Command('MULTIREDDITS')) @logged_in def multireddits(self): """ View a list of the user's subscribed multireddits """ self.selected_page = self.open_subscription_page('multireddit') @PageController.register(Command('PROMPT')) def prompt(self): """ Open a prompt to navigate to a different subreddit or comment" """ name = self.term.prompt_input('Enter page: /') if name: # Check if opening a submission url or a subreddit url # Example patterns for submissions: # comments/571dw3 # /comments/571dw3 # /r/pics/comments/571dw3/ # https://www.reddit.com/r/pics/comments/571dw3/at_disneyland submission_pattern = re.compile(r'(^|/)comments/(?P<id>.+?)($|/)') match = submission_pattern.search(name) if match: url = 'https://www.reddit.com/comments/{0}'.format(match.group('id')) self.selected_page = self.open_submission_page(url) else: self.selected_page = self.open_subreddit_page(name) @PageController.register(Command('INBOX')) @logged_in def inbox(self): """ View the user's inbox. """ self.selected_page = self.open_inbox_page('all') def open_inbox_page(self, content_type): """ Open an instance of the inbox page for the logged in user. """ from .inbox_page import InboxPage with self.term.loader('Loading inbox'): page = InboxPage(self.reddit, self.term, self.config, self.oauth, content_type=content_type) if not self.term.loader.exception: return page def open_subscription_page(self, content_type): """ Open an instance of the subscriptions page with the selected content. """ from .subscription_page import SubscriptionPage with self.term.loader('Loading {0}s'.format(content_type)): page = SubscriptionPage(self.reddit, self.term, self.config, self.oauth, content_type=content_type) if not self.term.loader.exception: return page def open_submission_page(self, url=None, submission=None): """ Open an instance of the submission page for the given submission URL. """ from .submission_page import SubmissionPage with self.term.loader('Loading submission'): page = SubmissionPage(self.reddit, self.term, self.config, self.oauth, url=url, submission=submission) if not self.term.loader.exception: return page def open_subreddit_page(self, name): """ Open an instance of the subreddit page for the given subreddit name. """ from .subreddit_page import SubredditPage with self.term.loader('Loading subreddit'): page = SubredditPage(self.reddit, self.term, self.config, self.oauth, name) if not self.term.loader.exception: return page def clear_input_queue(self): """ Clear excessive input caused by the scroll wheel or holding down a key """ with self.term.no_delay(): while self.term.getch() != -1: continue def draw(self): """ Clear the terminal screen and redraw all of the sub-windows """ n_rows, n_cols = self.term.stdscr.getmaxyx() if n_rows < self.term.MIN_HEIGHT or n_cols < self.term.MIN_WIDTH: # TODO: Will crash when you try to navigate if the terminal is too # small at startup because self._subwindows will never be populated return self._row = 0 self._draw_header() self._draw_banner() self._draw_content() self._draw_footer() self.term.clear_screen() self.term.stdscr.refresh() def _draw_header(self): """ Draw the title bar at the top of the screen """ n_rows, n_cols = self.term.stdscr.getmaxyx() # Note: 2 argument form of derwin breaks PDcurses on Windows 7! window = self.term.stdscr.derwin(1, n_cols, self._row, 0) window.erase() # curses.bkgd expects bytes in py2 and unicode in py3 window.bkgd(str(' '), self.term.attr('TitleBar')) sub_name = self.content.name sub_name = sub_name.replace('/r/front', 'Front Page') parts = sub_name.split('/') if len(parts) == 1: pass elif '/m/' in sub_name: _, _, user, _, multi = parts sub_name = '{} Curated by {}'.format(multi, user) elif parts[1] == 'u': noun = 'My' if parts[2] == 'me' else parts[2] + "'s" user_room = parts[3] if len(parts) == 4 else 'overview' title_lookup = { 'overview': 'Overview', 'submitted': 'Submissions', 'comments': 'Comments', 'saved': 'Saved Content', 'hidden': 'Hidden Content', 'upvoted': 'Upvoted Content', 'downvoted': 'Downvoted Content' } sub_name = "{} {}".format(noun, title_lookup[user_room]) query = self.content.query if query: sub_name = 'Searching {0}: {1}'.format(sub_name, query) self.term.add_line(window, sub_name, 0, 0) # Set the terminal title if len(sub_name) > 50: title = sub_name.strip('/') title = title.replace('_', ' ') try: title = title.rsplit('/', 1)[1] except IndexError: pass else: title = sub_name # Setting the terminal title will break emacs or systems without # X window. if os.getenv('DISPLAY') and not os.getenv('INSIDE_EMACS'): title += ' - rtv {0}'.format(__version__) title = self.term.clean(title) if six.PY3: # In py3 you can't write bytes to stdout title = title.decode('utf-8') title = '\x1b]2;{0}\x07'.format(title) else: title = b'\x1b]2;{0}\x07'.format(title) sys.stdout.write(title) sys.stdout.flush() if self.reddit and self.reddit.user is not None: # The starting position of the name depends on if we're converting # to ascii or not width = len if self.config['ascii'] else textual_width if self.config['hide_username']: username = "Logged in" else: username = self.reddit.user.name s_col = (n_cols - width(username) - 1) # Only print username if it fits in the empty space on the right if (s_col - 1) >= width(sub_name): self.term.add_line(window, username, 0, s_col) self._row += 1 def _draw_banner(self): """ Draw the banner with sorting options at the top of the page """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(1, n_cols, self._row, 0) window.erase() window.bkgd(str(' '), self.term.attr('OrderBar')) banner = docs.BANNER_SEARCH if self.content.query else self.BANNER items = banner.strip().split(' ') distance = (n_cols - sum(len(t) for t in items) - 1) / (len(items) - 1) spacing = max(1, int(distance)) * ' ' text = spacing.join(items) self.term.add_line(window, text, 0, 0) if self.content.order is not None: order = self.content.order.split('-')[0] col = text.find(order) - 3 attr = self.term.attr('OrderBarHighlight') window.chgat(0, col, 3, attr) self._row += 1 def _draw_content(self): """ Loop through submissions and fill up the content page. """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(n_rows - self._row - 1, n_cols, self._row, 0) window.erase() win_n_rows, win_n_cols = window.getmaxyx() self._subwindows = [] page_index, cursor_index, inverted = self.nav.position step = self.nav.step # If not inverted, align the first submission with the top and draw # downwards. If inverted, align the first submission with the bottom # and draw upwards. cancel_inverted = True current_row = (win_n_rows - 1) if inverted else 0 available_rows = win_n_rows top_item_height = None if inverted else self.nav.top_item_height for data in self.content.iterate(page_index, step, win_n_cols - 2): subwin_n_rows = min(available_rows, data['n_rows']) subwin_inverted = inverted if top_item_height is not None: # Special case: draw the page as non-inverted, except for the # top element. This element will be drawn as inverted with a # restricted height subwin_n_rows = min(subwin_n_rows, top_item_height) subwin_inverted = True top_item_height = None subwin_n_cols = win_n_cols - data['h_offset'] start = current_row - subwin_n_rows + 1 if inverted else current_row subwindow = window.derwin(subwin_n_rows, subwin_n_cols, start, data['h_offset']) self._subwindows.append((subwindow, data, subwin_inverted)) available_rows -= (subwin_n_rows + 1) # Add one for the blank line current_row += step * (subwin_n_rows + 1) if available_rows <= 0: # Indicate the page is full and we can keep the inverted screen. cancel_inverted = False break if len(self._subwindows) == 1: # Never draw inverted if only one subwindow. The top of the # subwindow should always be aligned with the top of the screen. cancel_inverted = True if cancel_inverted and self.nav.inverted: # In some cases we need to make sure that the screen is NOT # inverted. Unfortunately, this currently means drawing the whole # page over again. Could not think of a better way to pre-determine # if the content will fill up the page, given that it is dependent # on the size of the terminal. self.nav.flip((len(self._subwindows) - 1)) self._draw_content() return if self.nav.cursor_index >= len(self._subwindows): # Don't allow the cursor to go over the number of subwindows # This could happen if the window is resized and the cursor index is # pushed out of bounds self.nav.cursor_index = len(self._subwindows) - 1 # Now that the windows are setup, we can take a second pass through # to draw the text onto each subwindow for index, (win, data, inverted) in enumerate(self._subwindows): if self.nav.absolute_index >= 0 and index == self.nav.cursor_index: win.bkgd(str(' '), self.term.attr('Selected')) with self.term.theme.turn_on_selected(): self._draw_item(win, data, inverted) else: win.bkgd(str(' '), self.term.attr('Normal')) self._draw_item(win, data, inverted) self._row += win_n_rows def _draw_footer(self): """ Draw the key binds help bar at the bottom of the screen """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(1, n_cols, self._row, 0) window.erase() window.bkgd(str(' '), self.term.attr('HelpBar')) text = self.FOOTER.strip() self.term.add_line(window, text, 0, 0) self._row += 1 def _move_cursor(self, direction): # Note: ACS_VLINE doesn't like changing the attribute, so disregard the # redraw flag and opt to always redraw valid, redraw = self.nav.move(direction, len(self._subwindows)) if not valid: self.term.flash() def _move_page(self, direction): valid, redraw = self.nav.move_page(direction, len(self._subwindows)-1) if not valid: self.term.flash() def _prompt_period(self, order): choices = { '\n': order, '1': '{0}-hour'.format(order), '2': '{0}-day'.format(order), '3': '{0}-week'.format(order), '4': '{0}-month'.format(order), '5': '{0}-year'.format(order), '6': '{0}-all'.format(order)} message = docs.TIME_ORDER_MENU.strip().splitlines() ch = self.term.show_notification(message) ch = six.unichr(ch) return choices.get(ch)
mit
12b7b490658bf4edabd2d4b7abc232f0
34.562077
92
0.559191
4.204991
false
false
false
false
michael-lazar/rtv
tests/test_oauth.py
1
6890
# -*- coding: utf-8 -*- from __future__ import unicode_literals import requests from rtv.oauth import OAuthHelper, OAuthHandler from rtv.exceptions import InvalidRefreshToken from rtv.packages.praw.errors import OAuthException try: from unittest import mock except ImportError: import mock def test_oauth_handler_not_found(oauth_server): url = oauth_server.url + 'favicon.ico' resp = requests.get(url) assert resp.status_code == 404 def test_oauth_handler_no_callback(oauth_server): resp = requests.get(oauth_server.url) assert resp.status_code == 200 assert 'Wait...' in resp.text assert OAuthHandler.params['error'] is None def test_oauth_handler_access_denied(oauth_server): url = oauth_server.url + '?error=access_denied' resp = requests.get(url) assert resp.status_code == 200 assert OAuthHandler.params['error'] == 'access_denied' assert 'denied access' in resp.text def test_oauth_handler_error(oauth_server): url = oauth_server.url + '?error=fake' resp = requests.get(url) assert resp.status_code == 200 assert OAuthHandler.params['error'] == 'fake' assert 'fake' in resp.text def test_oauth_handler_success(oauth_server): url = oauth_server.url + '?state=fake_state&code=fake_code' resp = requests.get(url) assert resp.status_code == 200 assert OAuthHandler.params['error'] is None assert OAuthHandler.params['state'] == 'fake_state' assert OAuthHandler.params['code'] == 'fake_code' assert 'Access Granted' in resp.text def test_oauth_terminal_non_mobile_authorize(reddit, terminal, config): # Should direct to the desktop version if using a graphical browser reddit.config.API_PATHS['authorize'] = 'api/v1/authorize/' terminal._display = True oauth = OAuthHelper(reddit, terminal, config) assert '.compact' not in oauth.reddit.config.API_PATHS['authorize'] def test_oauth_terminal_mobile_authorize(reddit, terminal, config): # Should direct to the mobile version if using a terminal browser reddit.config.API_PATHS['authorize'] = 'api/v1/authorize/' terminal._display = False oauth = OAuthHelper(reddit, terminal, config) assert '.compact' in oauth.reddit.config.API_PATHS['authorize'] def test_oauth_authorize_invalid_token(oauth): oauth.config.refresh_token = 'invalid_token' oauth.authorize() assert isinstance(oauth.term.loader.exception, InvalidRefreshToken) assert oauth.server is None assert oauth.config.refresh_token is None def test_oauth_authorize_with_refresh_token(oauth, refresh_token): oauth.config.refresh_token = refresh_token oauth.authorize(autologin=True) assert oauth.server is None # We should be able to handle an oauth failure with mock.patch.object(oauth.reddit, 'refresh_access_information'): exception = OAuthException('', '') oauth.reddit.refresh_access_information.side_effect = exception oauth.authorize() assert isinstance(oauth.term.loader.exception, InvalidRefreshToken) assert oauth.server is None assert oauth.config.refresh_token is None def test_oauth_authorize_without_autologin(oauth, terminal, refresh_token): # The welcome message should be displayed when autologin is set to # false, even if we're using an existing refresh token and not performing # the whole login procedure. oauth.config.refresh_token = refresh_token oauth.authorize(autologin=False) text = 'Welcome civilization_phaze_3!'.encode('utf-8') terminal.stdscr.subwin.addstr.assert_any_call(1, 1, text) def test_oauth_clear_data(oauth): oauth.config.refresh_token = 'secrettoken' oauth.reddit.refresh_token = 'secrettoken' oauth.clear_oauth_data() assert oauth.config.refresh_token is None assert oauth.reddit.refresh_token is None def test_oauth_authorize(oauth, reddit, stdscr, refresh_token): # Because we use `from .helpers import open_browser` we have to patch the # function in the destination oauth module and not the helpers module with mock.patch('uuid.UUID.hex', new_callable=mock.PropertyMock) as uuid, \ mock.patch('rtv.terminal.Terminal.open_browser') as open_browser, \ mock.patch('rtv.oauth.OAuthHTTPServer') as http_server, \ mock.patch.object(oauth.reddit, 'user'), \ mock.patch('time.sleep'): # Valid authorization oauth.term._display = False params = {'state': 'uniqueid', 'code': 'secretcode', 'error': None} uuid.return_value = params['state'] def serve_forever(): oauth.params.update(**params) http_server.return_value.serve_forever.side_effect = serve_forever oauth.authorize() assert open_browser.called oauth.reddit.get_access_information.assert_called_with( reddit, params['code']) assert oauth.config.refresh_token is not None assert oauth.config.save_refresh_token.called stdscr.reset_mock() oauth.reddit.get_access_information.reset_mock() oauth.config.save_refresh_token.reset_mock() oauth.server = None # The next authorization should skip the oauth process oauth.config.refresh_token = refresh_token oauth.authorize() assert oauth.reddit.user is not None assert oauth.server is None stdscr.reset_mock() # Invalid state returned params = {'state': 'uniqueid', 'code': 'secretcode', 'error': None} oauth.config.refresh_token = None uuid.return_value = 'invalidcode' oauth.authorize() error_message = 'UUID mismatch'.encode('utf-8') stdscr.subwin.addstr.assert_any_call(1, 1, error_message) # Valid authorization, terminal browser oauth.term._display = True params = {'state': 'uniqueid', 'code': 'secretcode', 'error': None} uuid.return_value = params['state'] oauth.authorize() assert open_browser.called oauth.reddit.get_access_information.assert_called_with( reddit, params['code']) assert oauth.config.refresh_token is not None assert oauth.config.save_refresh_token.called stdscr.reset_mock() oauth.reddit.get_access_information.reset_mock() oauth.config.refresh_token = None oauth.config.save_refresh_token.reset_mock() oauth.server = None # Exceptions when logging in are handled correctly with mock.patch.object(oauth.reddit, 'get_access_information'): exception = OAuthException('', '') oauth.reddit.get_access_information.side_effect = exception oauth.authorize() assert isinstance(oauth.term.loader.exception, OAuthException) assert not oauth.config.save_refresh_token.called
mit
c63a561c00e88a7ec509877fb9aefb4b
34.153061
79
0.681713
3.939394
false
true
false
false
michael-lazar/rtv
rtv/config.py
1
10433
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import codecs import shutil import argparse from functools import partial import six from six.moves import configparser from . import docs, __version__ from .objects import KeyMap PACKAGE = os.path.dirname(__file__) HOME = os.path.expanduser('~') TEMPLATES = os.path.join(PACKAGE, 'templates') DEFAULT_CONFIG = os.path.join(TEMPLATES, 'rtv.cfg') DEFAULT_MAILCAP = os.path.join(TEMPLATES, 'mailcap') DEFAULT_THEMES = os.path.join(PACKAGE, 'themes') XDG_CONFIG_HOME = os.getenv('XDG_CONFIG_HOME', os.path.join(HOME, '.config')) XDG_DATA_HOME = os.getenv('XDG_DATA_HOME', os.path.join(HOME, '.local', 'share')) CONFIG = os.path.join(XDG_CONFIG_HOME, 'rtv', 'rtv.cfg') MAILCAP = os.path.join(HOME, '.mailcap') TOKEN = os.path.join(XDG_DATA_HOME, 'rtv', 'refresh-token') HISTORY = os.path.join(XDG_DATA_HOME, 'rtv', 'history.log') THEMES = os.path.join(XDG_CONFIG_HOME, 'rtv', 'themes') def build_parser(): parser = argparse.ArgumentParser( prog='rtv', description=docs.SUMMARY, epilog=docs.CONTROLS, usage=docs.USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( 'link', metavar='URL', nargs='?', help='[optional] Full URL of a submission to open') parser.add_argument( '-s', dest='subreddit', help='Name of the subreddit that will be loaded on start') parser.add_argument( '-l', dest='link_deprecated', help=argparse.SUPPRESS) # Deprecated, use the positional arg instead parser.add_argument( '--log', metavar='FILE', action='store', help='Log HTTP requests to the given file') parser.add_argument( '--config', metavar='FILE', action='store', help='Load configuration settings from the given file') parser.add_argument( '--ascii', action='store_const', const=True, help='Enable ascii-only mode') parser.add_argument( '--monochrome', action='store_const', const=True, help='Disable color') parser.add_argument( '--theme', metavar='FILE', action='store', help='Color theme to use, see --list-themes for valid options') parser.add_argument( '--list-themes', metavar='FILE', action='store_const', const=True, help='List all of the available color themes') parser.add_argument( '--non-persistent', dest='persistent', action='store_const', const=False, help='Forget the authenticated user when the program exits') parser.add_argument( '--no-autologin', dest='autologin', action='store_const', const=False, help='Do not authenticate automatically on startup') parser.add_argument( '--clear-auth', dest='clear_auth', action='store_const', const=True, help='Remove any saved user data before launching') parser.add_argument( '--copy-config', dest='copy_config', action='store_const', const=True, help='Copy the default configuration to {HOME}/.config/rtv/rtv.cfg') parser.add_argument( '--copy-mailcap', dest='copy_mailcap', action='store_const', const=True, help='Copy an example mailcap configuration to {HOME}/.mailcap') parser.add_argument( '--enable-media', dest='enable_media', action='store_const', const=True, help='Open external links using programs defined in the mailcap config') parser.add_argument( '-V', '--version', action='version', version='rtv ' + __version__) parser.add_argument( '--no-flash', dest='flash', action='store_const', const=False, help='Disable screen flashing') parser.add_argument( '--debug-info', dest='debug_info', action='store_const', const=True, help='Show system and environment information and exit') return parser def copy_default_mailcap(filename=MAILCAP): """ Copy the example mailcap configuration to the specified file. """ return _copy_settings_file(DEFAULT_MAILCAP, filename, 'mailcap') def copy_default_config(filename=CONFIG): """ Copy the default rtv user configuration to the specified file. """ return _copy_settings_file(DEFAULT_CONFIG, filename, 'config') def _copy_settings_file(source, destination, name): """ Copy a file from the repo to the user's home directory. """ if os.path.exists(destination): try: ch = six.moves.input( 'File %s already exists, overwrite? y/[n]):' % destination) if ch not in ('Y', 'y'): return except KeyboardInterrupt: return filepath = os.path.dirname(destination) if not os.path.exists(filepath): os.makedirs(filepath) print('Copying default %s to %s' % (name, destination)) shutil.copy(source, destination) os.chmod(destination, 0o664) class OrderedSet(object): """ A simple implementation of an ordered set. A set is used to check for membership, and a list is used to maintain ordering. """ def __init__(self, elements=None): elements = elements or [] self._set = set(elements) self._list = elements def __contains__(self, item): return item in self._set def __len__(self): return len(self._list) def __getitem__(self, item): return self._list[item] def add(self, item): self._set.add(item) self._list.append(item) class Config(object): """ This class manages the loading and saving of configs and other files. """ def __init__(self, history_file=HISTORY, token_file=TOKEN, **kwargs): self.history_file = history_file self.token_file = token_file self.config = kwargs default, bindings = self.get_file(DEFAULT_CONFIG) self.default = default self.keymap = KeyMap(bindings) # `refresh_token` and `history` are saved/loaded at separate locations, # so they are treated differently from the rest of the config options. self.refresh_token = None self.history = OrderedSet() def __getitem__(self, item): if item in self.config: return self.config[item] else: return self.default.get(item, None) def __setitem__(self, key, value): self.config[key] = value def __delitem__(self, key): self.config.pop(key, None) def update(self, **kwargs): self.config.update(kwargs) def load_refresh_token(self): if os.path.exists(self.token_file): with open(self.token_file) as fp: self.refresh_token = fp.read().strip() else: self.refresh_token = None def save_refresh_token(self): self._ensure_filepath(self.token_file) with open(self.token_file, 'w+') as fp: fp.write(self.refresh_token) def delete_refresh_token(self): if os.path.exists(self.token_file): os.remove(self.token_file) self.refresh_token = None def load_history(self): if os.path.exists(self.history_file): with codecs.open(self.history_file, encoding='utf-8') as fp: self.history = OrderedSet([line.strip() for line in fp]) else: self.history = OrderedSet() def save_history(self): self._ensure_filepath(self.history_file) with codecs.open(self.history_file, 'w+', encoding='utf-8') as fp: fp.writelines('\n'.join(self.history[-self['history_size']:])) def delete_history(self): if os.path.exists(self.history_file): os.remove(self.history_file) self.history = OrderedSet() @staticmethod def get_args(): """ Load settings from the command line. """ parser = build_parser() args = vars(parser.parse_args()) # Overwrite the deprecated "-l" option into the link variable if args['link_deprecated'] and args['link'] is None: args['link'] = args['link_deprecated'] args.pop('link_deprecated', None) # Filter out argument values that weren't supplied return {key: val for key, val in args.items() if val is not None} @classmethod def get_file(cls, filename=None): """ Load settings from an rtv configuration file. """ if filename is None: filename = CONFIG config = configparser.ConfigParser() if os.path.exists(filename): with codecs.open(filename, encoding='utf-8') as fp: config.readfp(fp) return cls._parse_rtv_file(config) @staticmethod def _parse_rtv_file(config): rtv = {} if config.has_section('rtv'): rtv = dict(config.items('rtv')) # convert non-string params to their typed representation params = { 'ascii': partial(config.getboolean, 'rtv'), 'monochrome': partial(config.getboolean, 'rtv'), 'persistent': partial(config.getboolean, 'rtv'), 'autologin': partial(config.getboolean, 'rtv'), 'clear_auth': partial(config.getboolean, 'rtv'), 'enable_media': partial(config.getboolean, 'rtv'), 'history_size': partial(config.getint, 'rtv'), 'oauth_redirect_port': partial(config.getint, 'rtv'), 'oauth_scope': lambda x: rtv[x].split(','), 'max_comment_cols': partial(config.getint, 'rtv'), 'max_pager_cols': partial(config.getint, 'rtv'), 'hide_username': partial(config.getboolean, 'rtv'), 'flash': partial(config.getboolean, 'rtv'), 'force_new_browser_window': partial(config.getboolean, 'rtv') } for key, func in params.items(): if key in rtv: rtv[key] = func(key) bindings = {} if config.has_section('bindings'): bindings = dict(config.items('bindings')) for name, keys in bindings.items(): bindings[name] = [key.strip() for key in keys.split(',')] return rtv, bindings @staticmethod def _ensure_filepath(filename): """ Ensure that the directory exists before trying to write to the file. """ filepath = os.path.dirname(filename) if not os.path.exists(filepath): os.makedirs(filepath)
mit
effee0d3d8d1db833639cd64b5ed2e3d
33.432343
81
0.612288
3.901645
false
true
false
false
wbond/asn1crypto
dev/_task.py
7
4196
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import ast import _ast import os import sys from . import package_root, task_keyword_args from ._import import _import_from if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes def _list_tasks(): """ Fetches a list of all valid tasks that may be run, and the args they accept. Does not actually import the task module to prevent errors if a user does not have the dependencies installed for every task. :return: A list of 2-element tuples: 0: a unicode string of the task name 1: a list of dicts containing the parameter definitions """ out = [] dev_path = os.path.join(package_root, 'dev') for fname in sorted(os.listdir(dev_path)): if fname.startswith('.') or fname.startswith('_'): continue if not fname.endswith('.py'): continue name = fname[:-3] args = () full_path = os.path.join(package_root, 'dev', fname) with open(full_path, 'rb') as f: full_code = f.read() if sys.version_info >= (3,): full_code = full_code.decode('utf-8') task_node = ast.parse(full_code, filename=full_path) for node in ast.iter_child_nodes(task_node): if isinstance(node, _ast.Assign): if len(node.targets) == 1 \ and isinstance(node.targets[0], _ast.Name) \ and node.targets[0].id == 'run_args': args = ast.literal_eval(node.value) break out.append((name, args)) return out def show_usage(): """ Prints to stderr the valid options for invoking tasks """ valid_tasks = [] for task in _list_tasks(): usage = task[0] for run_arg in task[1]: usage += ' ' name = run_arg.get('name', '') if run_arg.get('required', False): usage += '{%s}' % name else: usage += '[%s]' % name valid_tasks.append(usage) out = 'Usage: run.py' for karg in task_keyword_args: out += ' [%s=%s]' % (karg['name'], karg['placeholder']) out += ' (%s)' % ' | '.join(valid_tasks) print(out, file=sys.stderr) sys.exit(1) def _get_arg(num): """ :return: A unicode string of the requested command line arg """ if len(sys.argv) < num + 1: return None arg = sys.argv[num] if isinstance(arg, byte_cls): arg = arg.decode('utf-8') return arg def run_task(): """ Parses the command line args, invoking the requested task """ arg_num = 1 task = None args = [] kwargs = {} # We look for the task name, processing any global task keyword args # by setting the appropriate env var while True: val = _get_arg(arg_num) if val is None: break next_arg = False for karg in task_keyword_args: if val.startswith(karg['name'] + '='): os.environ[karg['env_var']] = val[len(karg['name']) + 1:] next_arg = True break if next_arg: arg_num += 1 continue task = val break if task is None: show_usage() task_mod = _import_from('dev.%s' % task, package_root, allow_error=True) if task_mod is None: show_usage() run_args = task_mod.__dict__.get('run_args', []) max_args = arg_num + 1 + len(run_args) if len(sys.argv) > max_args: show_usage() for i, run_arg in enumerate(run_args): val = _get_arg(arg_num + 1 + i) if val is None: if run_arg.get('required', False): show_usage() break if run_arg.get('cast') == 'int' and val.isdigit(): val = int(val) kwarg = run_arg.get('kwarg') if kwarg: kwargs[kwarg] = val else: args.append(val) run = task_mod.__dict__.get('run') result = run(*args, **kwargs) sys.exit(int(not result))
mit
dab3bb8f667726963873311cb43be3a4
24.742331
82
0.529075
3.73975
false
false
false
false
wbond/asn1crypto
asn1crypto/core.py
2
170716
# coding: utf-8 """ ASN.1 type classes for universal types. Exports the following items: - load() - Any() - Asn1Value() - BitString() - BMPString() - Boolean() - CharacterString() - Choice() - EmbeddedPdv() - Enumerated() - GeneralizedTime() - GeneralString() - GraphicString() - IA5String() - InstanceOf() - Integer() - IntegerBitString() - IntegerOctetString() - Null() - NumericString() - ObjectDescriptor() - ObjectIdentifier() - OctetBitString() - OctetString() - PrintableString() - Real() - RelativeOid() - Sequence() - SequenceOf() - Set() - SetOf() - TeletexString() - UniversalString() - UTCTime() - UTF8String() - VideotexString() - VisibleString() - VOID - Void() Other type classes are defined that help compose the types listed above. """ from __future__ import unicode_literals, division, absolute_import, print_function from datetime import datetime, timedelta from fractions import Fraction import binascii import copy import math import re import sys from . import _teletex_codec from ._errors import unwrap from ._ordereddict import OrderedDict from ._types import type_name, str_cls, byte_cls, int_types, chr_cls from .parser import _parse, _dump_header from .util import int_to_bytes, int_from_bytes, timezone, extended_datetime, create_timezone, utc_with_dst if sys.version_info <= (3,): from cStringIO import StringIO as BytesIO range = xrange # noqa _PY2 = True else: from io import BytesIO _PY2 = False _teletex_codec.register() CLASS_NUM_TO_NAME_MAP = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private', } CLASS_NAME_TO_NUM_MAP = { 'universal': 0, 'application': 1, 'context': 2, 'private': 3, 0: 0, 1: 1, 2: 2, 3: 3, } METHOD_NUM_TO_NAME_MAP = { 0: 'primitive', 1: 'constructed', } _OID_RE = re.compile(r'^\d+(\.\d+)*$') # A global tracker to ensure that _setup() is called for every class, even # if is has been called for a parent class. This allows different _fields # definitions for child classes. Without such a construct, the child classes # would just see the parent class attributes and would use them. _SETUP_CLASSES = {} def load(encoded_data, strict=False): """ Loads a BER/DER-encoded byte string and construct a universal object based on the tag value: - 1: Boolean - 2: Integer - 3: BitString - 4: OctetString - 5: Null - 6: ObjectIdentifier - 7: ObjectDescriptor - 8: InstanceOf - 9: Real - 10: Enumerated - 11: EmbeddedPdv - 12: UTF8String - 13: RelativeOid - 16: Sequence, - 17: Set - 18: NumericString - 19: PrintableString - 20: TeletexString - 21: VideotexString - 22: IA5String - 23: UTCTime - 24: GeneralizedTime - 25: GraphicString - 26: VisibleString - 27: GeneralString - 28: UniversalString - 29: CharacterString - 30: BMPString :param encoded_data: A byte string of BER or DER-encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :raises: ValueError - when strict is True and trailing data is present ValueError - when the encoded value tag a tag other than listed above ValueError - when the ASN.1 header length is longer than the data TypeError - when encoded_data is not a byte string :return: An instance of the one of the universal classes """ return Asn1Value.load(encoded_data, strict=strict) class Asn1Value(object): """ The basis of all ASN.1 values """ # The integer 0 for primitive, 1 for constructed method = None # An integer 0 through 3 - see CLASS_NUM_TO_NAME_MAP for value class_ = None # An integer 1 or greater indicating the tag number tag = None # An alternate tag allowed for this type - used for handling broken # structures where a string value is encoded using an incorrect tag _bad_tag = None # If the value has been implicitly tagged implicit = False # If explicitly tagged, a tuple of 2-element tuples containing the # class int and tag int, from innermost to outermost explicit = None # The BER/DER header bytes _header = None # Raw encoded value bytes not including class, method, tag, length header contents = None # The BER/DER trailer bytes _trailer = b'' # The native python representation of the value - this is not used by # some classes since they utilize _bytes or _unicode _native = None @classmethod def load(cls, encoded_data, strict=False, **kwargs): """ Loads a BER/DER-encoded byte string using the current class as the spec :param encoded_data: A byte string of BER or DER-encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: An instance of the current class """ if not isinstance(encoded_data, byte_cls): raise TypeError('encoded_data must be a byte string, not %s' % type_name(encoded_data)) spec = None if cls.tag is not None: spec = cls value, _ = _parse_build(encoded_data, spec=spec, spec_params=kwargs, strict=strict) return value def __init__(self, explicit=None, implicit=None, no_explicit=False, tag_type=None, class_=None, tag=None, optional=None, default=None, contents=None, method=None): """ The optional parameter is not used, but rather included so we don't have to delete it from the parameter dictionary when passing as keyword args :param explicit: An int tag number for explicit tagging, or a 2-element tuple of class and tag. :param implicit: An int tag number for implicit tagging, or a 2-element tuple of class and tag. :param no_explicit: If explicit tagging info should be removed from this instance. Used internally to allow contructing the underlying value that has been wrapped in an explicit tag. :param tag_type: None for normal values, or one of "implicit", "explicit" for tagged values. Deprecated in favor of explicit and implicit params. :param class_: The class for the value - defaults to "universal" if tag_type is None, otherwise defaults to "context". Valid values include: - "universal" - "application" - "context" - "private" Deprecated in favor of explicit and implicit params. :param tag: The integer tag to override - usually this is used with tag_type or class_. Deprecated in favor of explicit and implicit params. :param optional: Dummy parameter that allows "optional" key in spec param dicts :param default: The default value to use if the value is currently None :param contents: A byte string of the encoded contents of the value :param method: The method for the value - no default value since this is normally set on a class. Valid values include: - "primitive" or 0 - "constructed" or 1 :raises: ValueError - when implicit, explicit, tag_type, class_ or tag are invalid values """ try: if self.__class__ not in _SETUP_CLASSES: cls = self.__class__ # Allow explicit to be specified as a simple 2-element tuple # instead of requiring the user make a nested tuple if cls.explicit is not None and isinstance(cls.explicit[0], int_types): cls.explicit = (cls.explicit, ) if hasattr(cls, '_setup'): self._setup() _SETUP_CLASSES[cls] = True # Normalize tagging values if explicit is not None: if isinstance(explicit, int_types): if class_ is None: class_ = 'context' explicit = (class_, explicit) # Prevent both explicit and tag_type == 'explicit' if tag_type == 'explicit': tag_type = None tag = None if implicit is not None: if isinstance(implicit, int_types): if class_ is None: class_ = 'context' implicit = (class_, implicit) # Prevent both implicit and tag_type == 'implicit' if tag_type == 'implicit': tag_type = None tag = None # Convert old tag_type API to explicit/implicit params if tag_type is not None: if class_ is None: class_ = 'context' if tag_type == 'explicit': explicit = (class_, tag) elif tag_type == 'implicit': implicit = (class_, tag) else: raise ValueError(unwrap( ''' tag_type must be one of "implicit", "explicit", not %s ''', repr(tag_type) )) if explicit is not None: # Ensure we have a tuple of 2-element tuples if len(explicit) == 2 and isinstance(explicit[1], int_types): explicit = (explicit, ) for class_, tag in explicit: invalid_class = None if isinstance(class_, int_types): if class_ not in CLASS_NUM_TO_NAME_MAP: invalid_class = class_ else: if class_ not in CLASS_NAME_TO_NUM_MAP: invalid_class = class_ class_ = CLASS_NAME_TO_NUM_MAP[class_] if invalid_class is not None: raise ValueError(unwrap( ''' explicit class must be one of "universal", "application", "context", "private", not %s ''', repr(invalid_class) )) if tag is not None: if not isinstance(tag, int_types): raise TypeError(unwrap( ''' explicit tag must be an integer, not %s ''', type_name(tag) )) if self.explicit is None: self.explicit = ((class_, tag), ) else: self.explicit = self.explicit + ((class_, tag), ) elif implicit is not None: class_, tag = implicit if class_ not in CLASS_NAME_TO_NUM_MAP: raise ValueError(unwrap( ''' implicit class must be one of "universal", "application", "context", "private", not %s ''', repr(class_) )) if tag is not None: if not isinstance(tag, int_types): raise TypeError(unwrap( ''' implicit tag must be an integer, not %s ''', type_name(tag) )) self.class_ = CLASS_NAME_TO_NUM_MAP[class_] self.tag = tag self.implicit = True else: if class_ is not None: if class_ not in CLASS_NAME_TO_NUM_MAP: raise ValueError(unwrap( ''' class_ must be one of "universal", "application", "context", "private", not %s ''', repr(class_) )) self.class_ = CLASS_NAME_TO_NUM_MAP[class_] if self.class_ is None: self.class_ = 0 if tag is not None: self.tag = tag if method is not None: if method not in set(["primitive", 0, "constructed", 1]): raise ValueError(unwrap( ''' method must be one of "primitive" or "constructed", not %s ''', repr(method) )) if method == "primitive": method = 0 elif method == "constructed": method = 1 self.method = method if no_explicit: self.explicit = None if contents is not None: self.contents = contents elif default is not None: self.set(default) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e def __str__(self): """ Since str is different in Python 2 and 3, this calls the appropriate method, __unicode__() or __bytes__() :return: A unicode string """ if _PY2: return self.__bytes__() else: return self.__unicode__() def __repr__(self): """ :return: A unicode string """ if _PY2: return '<%s %s b%s>' % (type_name(self), id(self), repr(self.dump())) else: return '<%s %s %s>' % (type_name(self), id(self), repr(self.dump())) def __bytes__(self): """ A fall-back method for print() in Python 2 :return: A byte string of the output of repr() """ return self.__repr__().encode('utf-8') def __unicode__(self): """ A fall-back method for print() in Python 3 :return: A unicode string of the output of repr() """ return self.__repr__() def _new_instance(self): """ Constructs a new copy of the current object, preserving any tagging :return: An Asn1Value object """ new_obj = self.__class__() new_obj.class_ = self.class_ new_obj.tag = self.tag new_obj.implicit = self.implicit new_obj.explicit = self.explicit return new_obj def __copy__(self): """ Implements the copy.copy() interface :return: A new shallow copy of the current Asn1Value object """ new_obj = self._new_instance() new_obj._copy(self, copy.copy) return new_obj def __deepcopy__(self, memo): """ Implements the copy.deepcopy() interface :param memo: A dict for memoization :return: A new deep copy of the current Asn1Value object """ new_obj = self._new_instance() memo[id(self)] = new_obj new_obj._copy(self, copy.deepcopy) return new_obj def copy(self): """ Copies the object, preserving any special tagging from it :return: An Asn1Value object """ return copy.deepcopy(self) def retag(self, tagging, tag=None): """ Copies the object, applying a new tagging to it :param tagging: A dict containing the keys "explicit" and "implicit". Legacy API allows a unicode string of "implicit" or "explicit". :param tag: A integer tag number. Only used when tagging is a unicode string. :return: An Asn1Value object """ # This is required to preserve the old API if not isinstance(tagging, dict): tagging = {tagging: tag} new_obj = self.__class__(explicit=tagging.get('explicit'), implicit=tagging.get('implicit')) new_obj._copy(self, copy.deepcopy) return new_obj def untag(self): """ Copies the object, removing any special tagging from it :return: An Asn1Value object """ new_obj = self.__class__() new_obj._copy(self, copy.deepcopy) return new_obj def _copy(self, other, copy_func): """ Copies the contents of another Asn1Value object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ if self.__class__ != other.__class__: raise TypeError(unwrap( ''' Can not copy values from %s object to %s object ''', type_name(other), type_name(self) )) self.contents = other.contents self._native = copy_func(other._native) def debug(self, nest_level=1): """ Show the binary data and parsed data in a tree structure """ prefix = ' ' * nest_level # This interacts with Any and moves the tag, implicit, explicit, _header, # contents, _footer to the parsed value so duplicate data isn't present has_parsed = hasattr(self, 'parsed') _basic_debug(prefix, self) if has_parsed: self.parsed.debug(nest_level + 2) elif hasattr(self, 'chosen'): self.chosen.debug(nest_level + 2) else: if _PY2 and isinstance(self.native, byte_cls): print('%s Native: b%s' % (prefix, repr(self.native))) else: print('%s Native: %s' % (prefix, self.native)) def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ contents = self.contents # If the length is indefinite, force the re-encoding if self._header is not None and self._header[-1:] == b'\x80': force = True if self._header is None or force: if isinstance(self, Constructable) and self._indefinite: self.method = 0 header = _dump_header(self.class_, self.method, self.tag, self.contents) if self.explicit is not None: for class_, tag in self.explicit: header = _dump_header(class_, 1, tag, header + self.contents) + header self._header = header self._trailer = b'' return self._header + contents + self._trailer class ValueMap(): """ Basic functionality that allows for mapping values from ints or OIDs to python unicode strings """ # A dict from primitive value (int or OID) to unicode string. This needs # to be defined in the source code _map = None # A dict from unicode string to int/OID. This is automatically generated # from _map the first time it is needed _reverse_map = None def _setup(self): """ Generates _reverse_map from _map """ cls = self.__class__ if cls._map is None or cls._reverse_map is not None: return cls._reverse_map = {} for key, value in cls._map.items(): cls._reverse_map[value] = key class Castable(object): """ A mixin to handle converting an object between different classes that represent the same encoded value, but with different rules for converting to and from native Python values """ def cast(self, other_class): """ Converts the current object into an object of a different class. The new class must use the ASN.1 encoding for the value. :param other_class: The class to instantiate the new object from :return: An instance of the type other_class """ if other_class.tag != self.__class__.tag: raise TypeError(unwrap( ''' Can not covert a value from %s object to %s object since they use different tags: %d versus %d ''', type_name(other_class), type_name(self), other_class.tag, self.__class__.tag )) new_obj = other_class() new_obj.class_ = self.class_ new_obj.implicit = self.implicit new_obj.explicit = self.explicit new_obj._header = self._header new_obj.contents = self.contents new_obj._trailer = self._trailer if isinstance(self, Constructable): new_obj.method = self.method new_obj._indefinite = self._indefinite return new_obj class Constructable(object): """ A mixin to handle string types that may be constructed from chunks contained within an indefinite length BER-encoded container """ # Instance attribute indicating if an object was indefinite # length when parsed - affects parsing and dumping _indefinite = False def _merge_chunks(self): """ :return: A concatenation of the native values of the contained chunks """ if not self._indefinite: return self._as_chunk() pointer = 0 contents_len = len(self.contents) output = None while pointer < contents_len: # We pass the current class as the spec so content semantics are preserved sub_value, pointer = _parse_build(self.contents, pointer, spec=self.__class__) if output is None: output = sub_value._merge_chunks() else: output += sub_value._merge_chunks() if output is None: return self._as_chunk() return output def _as_chunk(self): """ A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples. """ return self.contents def _setable_native(self): """ Returns a native value that can be round-tripped into .set(), to result in a DER encoding. This differs from .native in that .native is designed for the end use, and may account for the fact that the merged value is further parsed as ASN.1, such as in the case of ParsableOctetString() and ParsableOctetBitString(). :return: A python value that is valid to pass to .set() """ return self.native def _copy(self, other, copy_func): """ Copies the contents of another Constructable object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Constructable, self)._copy(other, copy_func) # We really don't want to dump BER encodings, so if we see an # indefinite encoding, let's re-encode it if other._indefinite: self.set(other._setable_native()) class Void(Asn1Value): """ A representation of an optional value that is not present. Has .native property and .dump() method to be compatible with other value classes. """ contents = b'' def __eq__(self, other): """ :param other: The other Primitive to compare to :return: A boolean """ return other.__class__ == self.__class__ def __nonzero__(self): return False def __len__(self): return 0 def __iter__(self): return iter(()) @property def native(self): """ The native Python datatype representation of this value :return: None """ return None def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ return b'' VOID = Void() class Any(Asn1Value): """ A value class that can contain any value, and allows for easy parsing of the underlying encoded value using a spec. This is normally contained in a Structure that has an ObjectIdentifier field and _oid_pair and _oid_specs defined. """ # The parsed value object _parsed = None def __init__(self, value=None, **kwargs): """ Sets the value of the object before passing to Asn1Value.__init__() :param value: An Asn1Value object that will be set as the parsed value """ Asn1Value.__init__(self, **kwargs) try: if value is not None: if not isinstance(value, Asn1Value): raise TypeError(unwrap( ''' value must be an instance of Asn1Value, not %s ''', type_name(value) )) self._parsed = (value, value.__class__, None) self.contents = value.dump() except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e @property def native(self): """ The native Python datatype representation of this value :return: The .native value from the parsed value object """ if self._parsed is None: self.parse() return self._parsed[0].native @property def parsed(self): """ Returns the parsed object from .parse() :return: The object returned by .parse() """ if self._parsed is None: self.parse() return self._parsed[0] def parse(self, spec=None, spec_params=None): """ Parses the contents generically, or using a spec with optional params :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :return: An object of the type spec, or if not present, a child of Asn1Value """ if self._parsed is None or self._parsed[1:3] != (spec, spec_params): try: passed_params = spec_params or {} _tag_type_to_explicit_implicit(passed_params) if self.explicit is not None: if 'explicit' in passed_params: passed_params['explicit'] = self.explicit + passed_params['explicit'] else: passed_params['explicit'] = self.explicit contents = self._header + self.contents + self._trailer parsed_value, _ = _parse_build( contents, spec=spec, spec_params=passed_params ) self._parsed = (parsed_value, spec, spec_params) # Once we've parsed the Any value, clear any attributes from this object # since they are now duplicate self.tag = None self.explicit = None self.implicit = False self._header = b'' self.contents = contents self._trailer = b'' except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e return self._parsed[0] def _copy(self, other, copy_func): """ Copies the contents of another Any object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Any, self)._copy(other, copy_func) self._parsed = copy_func(other._parsed) def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ if self._parsed is None: self.parse() return self._parsed[0].dump(force=force) class Choice(Asn1Value): """ A class to handle when a value may be one of several options """ # The index in _alternatives of the validated alternative _choice = None # The name of the chosen alternative _name = None # The Asn1Value object for the chosen alternative _parsed = None # Choice overrides .contents to be a property so that the code expecting # the .contents attribute will get the .contents of the chosen alternative _contents = None # A list of tuples in one of the following forms. # # Option 1, a unicode string field name and a value class # # ("name", Asn1ValueClass) # # Option 2, same as Option 1, but with a dict of class params # # ("name", Asn1ValueClass, {'explicit': 5}) _alternatives = None # A dict that maps tuples of (class_, tag) to an index in _alternatives _id_map = None # A dict that maps alternative names to an index in _alternatives _name_map = None @classmethod def load(cls, encoded_data, strict=False, **kwargs): """ Loads a BER/DER-encoded byte string using the current class as the spec :param encoded_data: A byte string of BER or DER encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A instance of the current class """ if not isinstance(encoded_data, byte_cls): raise TypeError('encoded_data must be a byte string, not %s' % type_name(encoded_data)) value, _ = _parse_build(encoded_data, spec=cls, spec_params=kwargs, strict=strict) return value def _setup(self): """ Generates _id_map from _alternatives to allow validating contents """ cls = self.__class__ cls._id_map = {} cls._name_map = {} for index, info in enumerate(cls._alternatives): if len(info) < 3: info = info + ({},) cls._alternatives[index] = info id_ = _build_id_tuple(info[2], info[1]) cls._id_map[id_] = index cls._name_map[info[0]] = index def __init__(self, name=None, value=None, **kwargs): """ Checks to ensure implicit tagging is not being used since it is incompatible with Choice, then forwards on to Asn1Value.__init__() :param name: The name of the alternative to be set - used with value. Alternatively this may be a dict with a single key being the name and the value being the value, or a two-element tuple of the name and the value. :param value: The alternative value to set - used with name :raises: ValueError - when implicit param is passed (or legacy tag_type param is "implicit") """ _tag_type_to_explicit_implicit(kwargs) Asn1Value.__init__(self, **kwargs) try: if kwargs.get('implicit') is not None: raise ValueError(unwrap( ''' The Choice type can not be implicitly tagged even if in an implicit module - due to its nature any tagging must be explicit ''' )) if name is not None: if isinstance(name, dict): if len(name) != 1: raise ValueError(unwrap( ''' When passing a dict as the "name" argument to %s, it must have a single key/value - however %d were present ''', type_name(self), len(name) )) name, value = list(name.items())[0] if isinstance(name, tuple): if len(name) != 2: raise ValueError(unwrap( ''' When passing a tuple as the "name" argument to %s, it must have two elements, the name and value - however %d were present ''', type_name(self), len(name) )) value = name[1] name = name[0] if name not in self._name_map: raise ValueError(unwrap( ''' The name specified, "%s", is not a valid alternative for %s ''', name, type_name(self) )) self._choice = self._name_map[name] _, spec, params = self._alternatives[self._choice] if not isinstance(value, spec): value = spec(value, **params) else: value = _fix_tagging(value, params) self._parsed = value except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e @property def contents(self): """ :return: A byte string of the DER-encoded contents of the chosen alternative """ if self._parsed is not None: return self._parsed.contents return self._contents @contents.setter def contents(self, value): """ :param value: A byte string of the DER-encoded contents of the chosen alternative """ self._contents = value @property def name(self): """ :return: A unicode string of the field name of the chosen alternative """ if not self._name: self._name = self._alternatives[self._choice][0] return self._name def parse(self): """ Parses the detected alternative :return: An Asn1Value object of the chosen alternative """ if self._parsed is None: try: _, spec, params = self._alternatives[self._choice] self._parsed, _ = _parse_build(self._contents, spec=spec, spec_params=params) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e return self._parsed @property def chosen(self): """ :return: An Asn1Value object of the chosen alternative """ return self.parse() @property def native(self): """ The native Python datatype representation of this value :return: The .native value from the contained value object """ return self.chosen.native def validate(self, class_, tag, contents): """ Ensures that the class and tag specified exist as an alternative :param class_: The integer class_ from the encoded value header :param tag: The integer tag from the encoded value header :param contents: A byte string of the contents of the value - used when the object is explicitly tagged :raises: ValueError - when value is not a valid alternative """ id_ = (class_, tag) if self.explicit is not None: if self.explicit[-1] != id_: raise ValueError(unwrap( ''' %s was explicitly tagged, but the value provided does not match the class and tag ''', type_name(self) )) ((class_, _, tag, _, _, _), _) = _parse(contents, len(contents)) id_ = (class_, tag) if id_ in self._id_map: self._choice = self._id_map[id_] return # This means the Choice was implicitly tagged if self.class_ is not None and self.tag is not None: if len(self._alternatives) > 1: raise ValueError(unwrap( ''' %s was implicitly tagged, but more than one alternative exists ''', type_name(self) )) if id_ == (self.class_, self.tag): self._choice = 0 return asn1 = self._format_class_tag(class_, tag) asn1s = [self._format_class_tag(pair[0], pair[1]) for pair in self._id_map] raise ValueError(unwrap( ''' Value %s did not match the class and tag of any of the alternatives in %s: %s ''', asn1, type_name(self), ', '.join(asn1s) )) def _format_class_tag(self, class_, tag): """ :return: A unicode string of a human-friendly representation of the class and tag """ return '[%s %s]' % (CLASS_NUM_TO_NAME_MAP[class_].upper(), tag) def _copy(self, other, copy_func): """ Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Choice, self)._copy(other, copy_func) self._choice = other._choice self._name = other._name self._parsed = copy_func(other._parsed) def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ # If the length is indefinite, force the re-encoding if self._header is not None and self._header[-1:] == b'\x80': force = True self._contents = self.chosen.dump(force=force) if self._header is None or force: self._header = b'' if self.explicit is not None: for class_, tag in self.explicit: self._header = _dump_header(class_, 1, tag, self._header + self._contents) + self._header return self._header + self._contents class Concat(object): """ A class that contains two or more encoded child values concatentated together. THIS IS NOT PART OF THE ASN.1 SPECIFICATION! This exists to handle the x509.TrustedCertificate() class for OpenSSL certificates containing extra information. """ # A list of the specs of the concatenated values _child_specs = None _children = None @classmethod def load(cls, encoded_data, strict=False): """ Loads a BER/DER-encoded byte string using the current class as the spec :param encoded_data: A byte string of BER or DER encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A Concat object """ return cls(contents=encoded_data, strict=strict) def __init__(self, value=None, contents=None, strict=False): """ :param value: A native Python datatype to initialize the object value with :param contents: A byte string of the encoded contents of the value :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists in contents :raises: ValueError - when an error occurs with one of the children TypeError - when an error occurs with one of the children """ if contents is not None: try: contents_len = len(contents) self._children = [] offset = 0 for spec in self._child_specs: if offset < contents_len: child_value, offset = _parse_build(contents, pointer=offset, spec=spec) else: child_value = spec() self._children.append(child_value) if strict and offset != contents_len: extra_bytes = contents_len - offset raise ValueError('Extra data - %d bytes of trailing data were provided' % extra_bytes) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e if value is not None: if self._children is None: self._children = [None] * len(self._child_specs) for index, data in enumerate(value): self.__setitem__(index, data) def __str__(self): """ Since str is different in Python 2 and 3, this calls the appropriate method, __unicode__() or __bytes__() :return: A unicode string """ if _PY2: return self.__bytes__() else: return self.__unicode__() def __bytes__(self): """ A byte string of the DER-encoded contents """ return self.dump() def __unicode__(self): """ :return: A unicode string """ return repr(self) def __repr__(self): """ :return: A unicode string """ return '<%s %s %s>' % (type_name(self), id(self), repr(self.dump())) def __copy__(self): """ Implements the copy.copy() interface :return: A new shallow copy of the Concat object """ new_obj = self.__class__() new_obj._copy(self, copy.copy) return new_obj def __deepcopy__(self, memo): """ Implements the copy.deepcopy() interface :param memo: A dict for memoization :return: A new deep copy of the Concat object and all child objects """ new_obj = self.__class__() memo[id(self)] = new_obj new_obj._copy(self, copy.deepcopy) return new_obj def copy(self): """ Copies the object :return: A Concat object """ return copy.deepcopy(self) def _copy(self, other, copy_func): """ Copies the contents of another Concat object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ if self.__class__ != other.__class__: raise TypeError(unwrap( ''' Can not copy values from %s object to %s object ''', type_name(other), type_name(self) )) self._children = copy_func(other._children) def debug(self, nest_level=1): """ Show the binary data and parsed data in a tree structure """ prefix = ' ' * nest_level print('%s%s Object #%s' % (prefix, type_name(self), id(self))) print('%s Children:' % (prefix,)) for child in self._children: child.debug(nest_level + 2) def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ contents = b'' for child in self._children: contents += child.dump(force=force) return contents @property def contents(self): """ :return: A byte string of the DER-encoded contents of the children """ return self.dump() def __len__(self): """ :return: Integer """ return len(self._children) def __getitem__(self, key): """ Allows accessing children by index :param key: An integer of the child index :raises: KeyError - when an index is invalid :return: The Asn1Value object of the child specified """ if key > len(self._child_specs) - 1 or key < 0: raise KeyError(unwrap( ''' No child is definition for position %d of %s ''', key, type_name(self) )) return self._children[key] def __setitem__(self, key, value): """ Allows settings children by index :param key: An integer of the child index :param value: An Asn1Value object to set the child to :raises: KeyError - when an index is invalid ValueError - when the value is not an instance of Asn1Value """ if key > len(self._child_specs) - 1 or key < 0: raise KeyError(unwrap( ''' No child is defined for position %d of %s ''', key, type_name(self) )) if not isinstance(value, Asn1Value): raise ValueError(unwrap( ''' Value for child %s of %s is not an instance of asn1crypto.core.Asn1Value ''', key, type_name(self) )) self._children[key] = value def __iter__(self): """ :return: An iterator of child values """ return iter(self._children) class Primitive(Asn1Value): """ Sets the class_ and method attributes for primitive, universal values """ class_ = 0 method = 0 def __init__(self, value=None, default=None, contents=None, **kwargs): """ Sets the value of the object before passing to Asn1Value.__init__() :param value: A native Python datatype to initialize the object value with :param default: The default value if no value is specified :param contents: A byte string of the encoded contents of the value """ Asn1Value.__init__(self, **kwargs) try: if contents is not None: self.contents = contents elif value is not None: self.set(value) elif default is not None: self.set(default) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e def set(self, value): """ Sets the value of the object :param value: A byte string """ if not isinstance(value, byte_cls): raise TypeError(unwrap( ''' %s value must be a byte string, not %s ''', type_name(self), type_name(value) )) self._native = value self.contents = value self._header = None if self._trailer != b'': self._trailer = b'' def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ # If the length is indefinite, force the re-encoding if self._header is not None and self._header[-1:] == b'\x80': force = True if force: native = self.native self.contents = None self.set(native) return Asn1Value.dump(self) def __ne__(self, other): return not self == other def __eq__(self, other): """ :param other: The other Primitive to compare to :return: A boolean """ if not isinstance(other, Primitive): return False if self.contents != other.contents: return False # We compare class tag numbers since object tag numbers could be # different due to implicit or explicit tagging if self.__class__.tag != other.__class__.tag: return False if self.__class__ == other.__class__ and self.contents == other.contents: return True # If the objects share a common base class that is not too low-level # then we can compare the contents self_bases = (set(self.__class__.__bases__) | set([self.__class__])) - set([Asn1Value, Primitive, ValueMap]) other_bases = (set(other.__class__.__bases__) | set([other.__class__])) - set([Asn1Value, Primitive, ValueMap]) if self_bases | other_bases: return self.contents == other.contents # When tagging is going on, do the extra work of constructing new # objects to see if the dumped representation are the same if self.implicit or self.explicit or other.implicit or other.explicit: return self.untag().dump() == other.untag().dump() return self.dump() == other.dump() class AbstractString(Constructable, Primitive): """ A base class for all strings that have a known encoding. In general, we do not worry ourselves with confirming that the decoded values match a specific set of characters, only that they are decoded into a Python unicode string """ # The Python encoding name to use when decoding or encoded the contents _encoding = 'latin1' # Instance attribute of (possibly-merged) unicode string _unicode = None def set(self, value): """ Sets the value of the string :param value: A unicode string """ if not isinstance(value, str_cls): raise TypeError(unwrap( ''' %s value must be a unicode string, not %s ''', type_name(self), type_name(value) )) self._unicode = value self.contents = value.encode(self._encoding) self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' def __unicode__(self): """ :return: A unicode string """ if self.contents is None: return '' if self._unicode is None: self._unicode = self._merge_chunks().decode(self._encoding) return self._unicode def _copy(self, other, copy_func): """ Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(AbstractString, self)._copy(other, copy_func) self._unicode = other._unicode @property def native(self): """ The native Python datatype representation of this value :return: A unicode string or None """ if self.contents is None: return None return self.__unicode__() class Boolean(Primitive): """ Represents a boolean in both ASN.1 and Python """ tag = 1 def set(self, value): """ Sets the value of the object :param value: True, False or another value that works with bool() """ self._native = bool(value) self.contents = b'\x00' if not value else b'\xff' self._header = None if self._trailer != b'': self._trailer = b'' # Python 2 def __nonzero__(self): """ :return: True or False """ return self.__bool__() def __bool__(self): """ :return: True or False """ return self.contents != b'\x00' @property def native(self): """ The native Python datatype representation of this value :return: True, False or None """ if self.contents is None: return None if self._native is None: self._native = self.__bool__() return self._native class Integer(Primitive, ValueMap): """ Represents an integer in both ASN.1 and Python """ tag = 2 def set(self, value): """ Sets the value of the object :param value: An integer, or a unicode string if _map is set :raises: ValueError - when an invalid value is passed """ if isinstance(value, str_cls): if self._map is None: raise ValueError(unwrap( ''' %s value is a unicode string, but no _map provided ''', type_name(self) )) if value not in self._reverse_map: raise ValueError(unwrap( ''' %s value, %s, is not present in the _map ''', type_name(self), value )) value = self._reverse_map[value] elif not isinstance(value, int_types): raise TypeError(unwrap( ''' %s value must be an integer or unicode string when a name_map is provided, not %s ''', type_name(self), type_name(value) )) self._native = self._map[value] if self._map and value in self._map else value self.contents = int_to_bytes(value, signed=True) self._header = None if self._trailer != b'': self._trailer = b'' def __int__(self): """ :return: An integer """ return int_from_bytes(self.contents, signed=True) @property def native(self): """ The native Python datatype representation of this value :return: An integer or None """ if self.contents is None: return None if self._native is None: self._native = self.__int__() if self._map is not None and self._native in self._map: self._native = self._map[self._native] return self._native class _IntegerBitString(object): """ A mixin for IntegerBitString and BitString to parse the contents as an integer. """ # Tuple of 1s and 0s; set through native _unused_bits = () def _as_chunk(self): """ Parse the contents of a primitive BitString encoding as an integer value. Allows reconstructing indefinite length values. :raises: ValueError - when an invalid value is passed :return: A list with one tuple (value, bits, unused_bits) where value is an integer with the value of the BitString, bits is the bit count of value and unused_bits is a tuple of 1s and 0s. """ if self._indefinite: # return an empty chunk, for cases like \x23\x80\x00\x00 return [] unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0] value = int_from_bytes(self.contents[1:]) bits = (len(self.contents) - 1) * 8 if not unused_bits_len: return [(value, bits, ())] if len(self.contents) == 1: # Disallowed by X.690 §8.6.2.3 raise ValueError('Empty bit string has {0} unused bits'.format(unused_bits_len)) if unused_bits_len > 7: # Disallowed by X.690 §8.6.2.2 raise ValueError('Bit string has {0} unused bits'.format(unused_bits_len)) unused_bits = _int_to_bit_tuple(value & ((1 << unused_bits_len) - 1), unused_bits_len) value >>= unused_bits_len bits -= unused_bits_len return [(value, bits, unused_bits)] def _chunks_to_int(self): """ Combines the chunks into a single value. :raises: ValueError - when an invalid value is passed :return: A tuple (value, bits, unused_bits) where value is an integer with the value of the BitString, bits is the bit count of value and unused_bits is a tuple of 1s and 0s. """ if not self._indefinite: # Fast path return self._as_chunk()[0] value = 0 total_bits = 0 unused_bits = () # X.690 §8.6.3 allows empty indefinite encodings for chunk, bits, unused_bits in self._merge_chunks(): if total_bits & 7: # Disallowed by X.690 §8.6.4 raise ValueError('Only last chunk in a bit string may have unused bits') total_bits += bits value = (value << bits) | chunk return value, total_bits, unused_bits def _copy(self, other, copy_func): """ Copies the contents of another _IntegerBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(_IntegerBitString, self)._copy(other, copy_func) self._unused_bits = other._unused_bits @property def unused_bits(self): """ The unused bits of the bit string encoding. :return: A tuple of 1s and 0s """ # call native to set _unused_bits self.native return self._unused_bits class BitString(_IntegerBitString, Constructable, Castable, Primitive, ValueMap): """ Represents a bit string from ASN.1 as a Python tuple of 1s and 0s """ tag = 3 _size = None def _setup(self): """ Generates _reverse_map from _map """ ValueMap._setup(self) cls = self.__class__ if cls._map is not None: cls._size = max(self._map.keys()) + 1 def set(self, value): """ Sets the value of the object :param value: An integer or a tuple of integers 0 and 1 :raises: ValueError - when an invalid value is passed """ if isinstance(value, set): if self._map is None: raise ValueError(unwrap( ''' %s._map has not been defined ''', type_name(self) )) bits = [0] * self._size self._native = value for index in range(0, self._size): key = self._map.get(index) if key is None: continue if key in value: bits[index] = 1 value = ''.join(map(str_cls, bits)) elif value.__class__ == tuple: if self._map is None: self._native = value else: self._native = set() for index, bit in enumerate(value): if bit: name = self._map.get(index, index) self._native.add(name) value = ''.join(map(str_cls, value)) else: raise TypeError(unwrap( ''' %s value must be a tuple of ones and zeros or a set of unicode strings, not %s ''', type_name(self), type_name(value) )) if self._map is not None: if len(value) > self._size: raise ValueError(unwrap( ''' %s value must be at most %s bits long, specified was %s long ''', type_name(self), self._size, len(value) )) # A NamedBitList must have trailing zero bit truncated. See # https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf # section 11.2, # https://tools.ietf.org/html/rfc5280#page-134 and # https://www.ietf.org/mail-archive/web/pkix/current/msg10443.html value = value.rstrip('0') size = len(value) size_mod = size % 8 extra_bits = 0 if size_mod != 0: extra_bits = 8 - size_mod value += '0' * extra_bits size_in_bytes = int(math.ceil(size / 8)) if extra_bits: extra_bits_byte = int_to_bytes(extra_bits) else: extra_bits_byte = b'\x00' if value == '': value_bytes = b'' else: value_bytes = int_to_bytes(int(value, 2)) if len(value_bytes) != size_in_bytes: value_bytes = (b'\x00' * (size_in_bytes - len(value_bytes))) + value_bytes self.contents = extra_bits_byte + value_bytes self._unused_bits = (0,) * extra_bits self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' def __getitem__(self, key): """ Retrieves a boolean version of one of the bits based on a name from the _map :param key: The unicode string of one of the bit names :raises: ValueError - when _map is not set or the key name is invalid :return: A boolean if the bit is set """ is_int = isinstance(key, int_types) if not is_int: if not isinstance(self._map, dict): raise ValueError(unwrap( ''' %s._map has not been defined ''', type_name(self) )) if key not in self._reverse_map: raise ValueError(unwrap( ''' %s._map does not contain an entry for "%s" ''', type_name(self), key )) if self._native is None: self.native if self._map is None: if len(self._native) >= key + 1: return bool(self._native[key]) return False if is_int: key = self._map.get(key, key) return key in self._native def __setitem__(self, key, value): """ Sets one of the bits based on a name from the _map :param key: The unicode string of one of the bit names :param value: A boolean value :raises: ValueError - when _map is not set or the key name is invalid """ is_int = isinstance(key, int_types) if not is_int: if self._map is None: raise ValueError(unwrap( ''' %s._map has not been defined ''', type_name(self) )) if key not in self._reverse_map: raise ValueError(unwrap( ''' %s._map does not contain an entry for "%s" ''', type_name(self), key )) if self._native is None: self.native if self._map is None: new_native = list(self._native) max_key = len(new_native) - 1 if key > max_key: new_native.extend([0] * (key - max_key)) new_native[key] = 1 if value else 0 self._native = tuple(new_native) else: if is_int: key = self._map.get(key, key) if value: if key not in self._native: self._native.add(key) else: if key in self._native: self._native.remove(key) self.set(self._native) @property def native(self): """ The native Python datatype representation of this value :return: If a _map is set, a set of names, or if no _map is set, a tuple of integers 1 and 0. None if no value. """ # For BitString we default the value to be all zeros if self.contents is None: if self._map is None: self.set(()) else: self.set(set()) if self._native is None: int_value, bit_count, self._unused_bits = self._chunks_to_int() bits = _int_to_bit_tuple(int_value, bit_count) if self._map: self._native = set() for index, bit in enumerate(bits): if bit: name = self._map.get(index, index) self._native.add(name) else: self._native = bits return self._native class OctetBitString(Constructable, Castable, Primitive): """ Represents a bit string in ASN.1 as a Python byte string """ tag = 3 # Instance attribute of (possibly-merged) byte string _bytes = None # Tuple of 1s and 0s; set through native _unused_bits = () def set(self, value): """ Sets the value of the object :param value: A byte string :raises: ValueError - when an invalid value is passed """ if not isinstance(value, byte_cls): raise TypeError(unwrap( ''' %s value must be a byte string, not %s ''', type_name(self), type_name(value) )) self._bytes = value # Set the unused bits to 0 self.contents = b'\x00' + value self._unused_bits = () self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' def __bytes__(self): """ :return: A byte string """ if self.contents is None: return b'' if self._bytes is None: if not self._indefinite: self._bytes, self._unused_bits = self._as_chunk()[0] else: chunks = self._merge_chunks() self._unused_bits = () for chunk in chunks: if self._unused_bits: # Disallowed by X.690 §8.6.4 raise ValueError('Only last chunk in a bit string may have unused bits') self._unused_bits = chunk[1] self._bytes = b''.join(chunk[0] for chunk in chunks) return self._bytes def _copy(self, other, copy_func): """ Copies the contents of another OctetBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(OctetBitString, self)._copy(other, copy_func) self._bytes = other._bytes self._unused_bits = other._unused_bits def _as_chunk(self): """ Allows reconstructing indefinite length values :raises: ValueError - when an invalid value is passed :return: List with one tuple, consisting of a byte string and an integer (unused bits) """ unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0] if not unused_bits_len: return [(self.contents[1:], ())] if len(self.contents) == 1: # Disallowed by X.690 §8.6.2.3 raise ValueError('Empty bit string has {0} unused bits'.format(unused_bits_len)) if unused_bits_len > 7: # Disallowed by X.690 §8.6.2.2 raise ValueError('Bit string has {0} unused bits'.format(unused_bits_len)) mask = (1 << unused_bits_len) - 1 last_byte = ord(self.contents[-1]) if _PY2 else self.contents[-1] # zero out the unused bits in the last byte. zeroed_byte = last_byte & ~mask value = self.contents[1:-1] + (chr(zeroed_byte) if _PY2 else bytes((zeroed_byte,))) unused_bits = _int_to_bit_tuple(last_byte & mask, unused_bits_len) return [(value, unused_bits)] @property def native(self): """ The native Python datatype representation of this value :return: A byte string or None """ if self.contents is None: return None return self.__bytes__() @property def unused_bits(self): """ The unused bits of the bit string encoding. :return: A tuple of 1s and 0s """ # call native to set _unused_bits self.native return self._unused_bits class IntegerBitString(_IntegerBitString, Constructable, Castable, Primitive): """ Represents a bit string in ASN.1 as a Python integer """ tag = 3 def set(self, value): """ Sets the value of the object :param value: An integer :raises: ValueError - when an invalid value is passed """ if not isinstance(value, int_types): raise TypeError(unwrap( ''' %s value must be a positive integer, not %s ''', type_name(self), type_name(value) )) if value < 0: raise ValueError(unwrap( ''' %s value must be a positive integer, not %d ''', type_name(self), value )) self._native = value # Set the unused bits to 0 self.contents = b'\x00' + int_to_bytes(value, signed=True) self._unused_bits = () self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' @property def native(self): """ The native Python datatype representation of this value :return: An integer or None """ if self.contents is None: return None if self._native is None: self._native, __, self._unused_bits = self._chunks_to_int() return self._native class OctetString(Constructable, Castable, Primitive): """ Represents a byte string in both ASN.1 and Python """ tag = 4 # Instance attribute of (possibly-merged) byte string _bytes = None def set(self, value): """ Sets the value of the object :param value: A byte string """ if not isinstance(value, byte_cls): raise TypeError(unwrap( ''' %s value must be a byte string, not %s ''', type_name(self), type_name(value) )) self._bytes = value self.contents = value self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' def __bytes__(self): """ :return: A byte string """ if self.contents is None: return b'' if self._bytes is None: self._bytes = self._merge_chunks() return self._bytes def _copy(self, other, copy_func): """ Copies the contents of another OctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(OctetString, self)._copy(other, copy_func) self._bytes = other._bytes @property def native(self): """ The native Python datatype representation of this value :return: A byte string or None """ if self.contents is None: return None return self.__bytes__() class IntegerOctetString(Constructable, Castable, Primitive): """ Represents a byte string in ASN.1 as a Python integer """ tag = 4 # An explicit length in bytes the integer should be encoded to. This should # generally not be used since DER defines a canonical encoding, however some # use of this, such as when storing elliptic curve private keys, requires an # exact number of bytes, even if the leading bytes are null. _encoded_width = None def set(self, value): """ Sets the value of the object :param value: An integer :raises: ValueError - when an invalid value is passed """ if not isinstance(value, int_types): raise TypeError(unwrap( ''' %s value must be a positive integer, not %s ''', type_name(self), type_name(value) )) if value < 0: raise ValueError(unwrap( ''' %s value must be a positive integer, not %d ''', type_name(self), value )) self._native = value self.contents = int_to_bytes(value, signed=False, width=self._encoded_width) self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' @property def native(self): """ The native Python datatype representation of this value :return: An integer or None """ if self.contents is None: return None if self._native is None: self._native = int_from_bytes(self._merge_chunks()) return self._native def set_encoded_width(self, width): """ Set the explicit enoding width for the integer :param width: An integer byte width to encode the integer to """ self._encoded_width = width # Make sure the encoded value is up-to-date with the proper width if self.contents is not None and len(self.contents) != width: self.set(self.native) class ParsableOctetString(Constructable, Castable, Primitive): tag = 4 _parsed = None # Instance attribute of (possibly-merged) byte string _bytes = None def __init__(self, value=None, parsed=None, **kwargs): """ Allows providing a parsed object that will be serialized to get the byte string value :param value: A native Python datatype to initialize the object value with :param parsed: If value is None and this is an Asn1Value object, this will be set as the parsed value, and the value will be obtained by calling .dump() on this object. """ set_parsed = False if value is None and parsed is not None and isinstance(parsed, Asn1Value): value = parsed.dump() set_parsed = True Primitive.__init__(self, value=value, **kwargs) if set_parsed: self._parsed = (parsed, parsed.__class__, None) def set(self, value): """ Sets the value of the object :param value: A byte string """ if not isinstance(value, byte_cls): raise TypeError(unwrap( ''' %s value must be a byte string, not %s ''', type_name(self), type_name(value) )) self._bytes = value self.contents = value self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' def parse(self, spec=None, spec_params=None): """ Parses the contents generically, or using a spec with optional params :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :return: An object of the type spec, or if not present, a child of Asn1Value """ if self._parsed is None or self._parsed[1:3] != (spec, spec_params): parsed_value, _ = _parse_build(self.__bytes__(), spec=spec, spec_params=spec_params) self._parsed = (parsed_value, spec, spec_params) return self._parsed[0] def __bytes__(self): """ :return: A byte string """ if self.contents is None: return b'' if self._bytes is None: self._bytes = self._merge_chunks() return self._bytes def _setable_native(self): """ Returns a byte string that can be passed into .set() :return: A python value that is valid to pass to .set() """ return self.__bytes__() def _copy(self, other, copy_func): """ Copies the contents of another ParsableOctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(ParsableOctetString, self)._copy(other, copy_func) self._bytes = other._bytes self._parsed = copy_func(other._parsed) @property def native(self): """ The native Python datatype representation of this value :return: A byte string or None """ if self.contents is None: return None if self._parsed is not None: return self._parsed[0].native else: return self.__bytes__() @property def parsed(self): """ Returns the parsed object from .parse() :return: The object returned by .parse() """ if self._parsed is None: self.parse() return self._parsed[0] def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ # If the length is indefinite, force the re-encoding if self._indefinite: force = True if force: if self._parsed is not None: native = self.parsed.dump(force=force) else: native = self.native self.contents = None self.set(native) return Asn1Value.dump(self) class ParsableOctetBitString(ParsableOctetString): tag = 3 def set(self, value): """ Sets the value of the object :param value: A byte string :raises: ValueError - when an invalid value is passed """ if not isinstance(value, byte_cls): raise TypeError(unwrap( ''' %s value must be a byte string, not %s ''', type_name(self), type_name(value) )) self._bytes = value # Set the unused bits to 0 self.contents = b'\x00' + value self._header = None if self._indefinite: self._indefinite = False self.method = 0 if self._trailer != b'': self._trailer = b'' def _as_chunk(self): """ Allows reconstructing indefinite length values :raises: ValueError - when an invalid value is passed :return: A byte string """ unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0] if unused_bits_len: raise ValueError('ParsableOctetBitString should have no unused bits') return self.contents[1:] class Null(Primitive): """ Represents a null value in ASN.1 as None in Python """ tag = 5 contents = b'' def set(self, value): """ Sets the value of the object :param value: None """ self.contents = b'' @property def native(self): """ The native Python datatype representation of this value :return: None """ return None class ObjectIdentifier(Primitive, ValueMap): """ Represents an object identifier in ASN.1 as a Python unicode dotted integer string """ tag = 6 # A unicode string of the dotted form of the object identifier _dotted = None @classmethod def map(cls, value): """ Converts a dotted unicode string OID into a mapped unicode string :param value: A dotted unicode string OID :raises: ValueError - when no _map dict has been defined on the class TypeError - when value is not a unicode string :return: A mapped unicode string """ if cls._map is None: raise ValueError(unwrap( ''' %s._map has not been defined ''', type_name(cls) )) if not isinstance(value, str_cls): raise TypeError(unwrap( ''' value must be a unicode string, not %s ''', type_name(value) )) return cls._map.get(value, value) @classmethod def unmap(cls, value): """ Converts a mapped unicode string value into a dotted unicode string OID :param value: A mapped unicode string OR dotted unicode string OID :raises: ValueError - when no _map dict has been defined on the class or the value can't be unmapped TypeError - when value is not a unicode string :return: A dotted unicode string OID """ if cls not in _SETUP_CLASSES: cls()._setup() _SETUP_CLASSES[cls] = True if cls._map is None: raise ValueError(unwrap( ''' %s._map has not been defined ''', type_name(cls) )) if not isinstance(value, str_cls): raise TypeError(unwrap( ''' value must be a unicode string, not %s ''', type_name(value) )) if value in cls._reverse_map: return cls._reverse_map[value] if not _OID_RE.match(value): raise ValueError(unwrap( ''' %s._map does not contain an entry for "%s" ''', type_name(cls), value )) return value def set(self, value): """ Sets the value of the object :param value: A unicode string. May be a dotted integer string, or if _map is provided, one of the mapped values. :raises: ValueError - when an invalid value is passed """ if not isinstance(value, str_cls): raise TypeError(unwrap( ''' %s value must be a unicode string, not %s ''', type_name(self), type_name(value) )) self._native = value if self._map is not None: if value in self._reverse_map: value = self._reverse_map[value] self.contents = b'' first = None for index, part in enumerate(value.split('.')): part = int(part) # The first two parts are merged into a single byte if index == 0: first = part continue elif index == 1: if first > 2: raise ValueError(unwrap( ''' First arc must be one of 0, 1 or 2, not %s ''', repr(first) )) elif first < 2 and part >= 40: raise ValueError(unwrap( ''' Second arc must be less than 40 if first arc is 0 or 1, not %s ''', repr(part) )) part = (first * 40) + part encoded_part = chr_cls(0x7F & part) part = part >> 7 while part > 0: encoded_part = chr_cls(0x80 | (0x7F & part)) + encoded_part part = part >> 7 self.contents += encoded_part self._header = None if self._trailer != b'': self._trailer = b'' def __unicode__(self): """ :return: A unicode string """ return self.dotted @property def dotted(self): """ :return: A unicode string of the object identifier in dotted notation, thus ignoring any mapped value """ if self._dotted is None: output = [] part = 0 for byte in self.contents: if _PY2: byte = ord(byte) part = part * 128 part += byte & 127 # Last byte in subidentifier has the eighth bit set to 0 if byte & 0x80 == 0: if len(output) == 0: if part >= 80: output.append(str_cls(2)) output.append(str_cls(part - 80)) elif part >= 40: output.append(str_cls(1)) output.append(str_cls(part - 40)) else: output.append(str_cls(0)) output.append(str_cls(part)) else: output.append(str_cls(part)) part = 0 self._dotted = '.'.join(output) return self._dotted @property def native(self): """ The native Python datatype representation of this value :return: A unicode string or None. If _map is not defined, the unicode string is a string of dotted integers. If _map is defined and the dotted string is present in the _map, the mapped value is returned. """ if self.contents is None: return None if self._native is None: self._native = self.dotted if self._map is not None and self._native in self._map: self._native = self._map[self._native] return self._native class ObjectDescriptor(Primitive): """ Represents an object descriptor from ASN.1 - no Python implementation """ tag = 7 class InstanceOf(Primitive): """ Represents an instance from ASN.1 - no Python implementation """ tag = 8 class Real(Primitive): """ Represents a real number from ASN.1 - no Python implementation """ tag = 9 class Enumerated(Integer): """ Represents a enumerated list of integers from ASN.1 as a Python unicode string """ tag = 10 def set(self, value): """ Sets the value of the object :param value: An integer or a unicode string from _map :raises: ValueError - when an invalid value is passed """ if not isinstance(value, int_types) and not isinstance(value, str_cls): raise TypeError(unwrap( ''' %s value must be an integer or a unicode string, not %s ''', type_name(self), type_name(value) )) if isinstance(value, str_cls): if value not in self._reverse_map: raise ValueError(unwrap( ''' %s value "%s" is not a valid value ''', type_name(self), value )) value = self._reverse_map[value] elif value not in self._map: raise ValueError(unwrap( ''' %s value %s is not a valid value ''', type_name(self), value )) Integer.set(self, value) @property def native(self): """ The native Python datatype representation of this value :return: A unicode string or None """ if self.contents is None: return None if self._native is None: self._native = self._map[self.__int__()] return self._native class UTF8String(AbstractString): """ Represents a UTF-8 string from ASN.1 as a Python unicode string """ tag = 12 _encoding = 'utf-8' class RelativeOid(ObjectIdentifier): """ Represents an object identifier in ASN.1 as a Python unicode dotted integer string """ tag = 13 class Sequence(Asn1Value): """ Represents a sequence of fields from ASN.1 as a Python object with a dict-like interface """ tag = 16 class_ = 0 method = 1 # A list of child objects, in order of _fields children = None # Sequence overrides .contents to be a property so that the mutated state # of child objects can be checked to ensure everything is up-to-date _contents = None # Variable to track if the object has been mutated _mutated = False # A list of tuples in one of the following forms. # # Option 1, a unicode string field name and a value class # # ("name", Asn1ValueClass) # # Option 2, same as Option 1, but with a dict of class params # # ("name", Asn1ValueClass, {'explicit': 5}) _fields = [] # A dict with keys being the name of a field and the value being a unicode # string of the method name on self to call to get the spec for that field _spec_callbacks = None # A dict that maps unicode string field names to an index in _fields _field_map = None # A list in the same order as _fields that has tuples in the form (class_, tag) _field_ids = None # An optional 2-element tuple that defines the field names of an OID field # and the field that the OID should be used to help decode. Works with the # _oid_specs attribute. _oid_pair = None # A dict with keys that are unicode string OID values and values that are # Asn1Value classes to use for decoding a variable-type field. _oid_specs = None # A 2-element tuple of the indexes in _fields of the OID and value fields _oid_nums = None # Predetermined field specs to optimize away calls to _determine_spec() _precomputed_specs = None def __init__(self, value=None, default=None, **kwargs): """ Allows setting field values before passing everything else along to Asn1Value.__init__() :param value: A native Python datatype to initialize the object value with :param default: The default value if no value is specified """ Asn1Value.__init__(self, **kwargs) check_existing = False if value is None and default is not None: check_existing = True if self.children is None: if self.contents is None: check_existing = False else: self._parse_children() value = default if value is not None: try: # Fields are iterated in definition order to allow things like # OID-based specs. Otherwise sometimes the value would be processed # before the OID field, resulting in invalid value object creation. if self._fields: keys = [info[0] for info in self._fields] unused_keys = set(value.keys()) else: keys = value.keys() unused_keys = set(keys) for key in keys: # If we are setting defaults, but a real value has already # been set for the field, then skip it if check_existing: index = self._field_map[key] if index < len(self.children) and self.children[index] is not VOID: if key in unused_keys: unused_keys.remove(key) continue if key in value: self.__setitem__(key, value[key]) unused_keys.remove(key) if len(unused_keys): raise ValueError(unwrap( ''' One or more unknown fields was passed to the constructor of %s: %s ''', type_name(self), ', '.join(sorted(list(unused_keys))) )) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e @property def contents(self): """ :return: A byte string of the DER-encoded contents of the sequence """ if self.children is None: return self._contents if self._is_mutated(): self._set_contents() return self._contents @contents.setter def contents(self, value): """ :param value: A byte string of the DER-encoded contents of the sequence """ self._contents = value def _is_mutated(self): """ :return: A boolean - if the sequence or any children (recursively) have been mutated """ mutated = self._mutated if self.children is not None: for child in self.children: if isinstance(child, Sequence) or isinstance(child, SequenceOf): mutated = mutated or child._is_mutated() return mutated def _lazy_child(self, index): """ Builds a child object if the child has only been parsed into a tuple so far """ child = self.children[index] if child.__class__ == tuple: child = self.children[index] = _build(*child) return child def __len__(self): """ :return: Integer """ # We inline this check to prevent method invocation each time if self.children is None: self._parse_children() return len(self.children) def __getitem__(self, key): """ Allows accessing fields by name or index :param key: A unicode string of the field name, or an integer of the field index :raises: KeyError - when a field name or index is invalid :return: The Asn1Value object of the field specified """ # We inline this check to prevent method invocation each time if self.children is None: self._parse_children() if not isinstance(key, int_types): if key not in self._field_map: raise KeyError(unwrap( ''' No field named "%s" defined for %s ''', key, type_name(self) )) key = self._field_map[key] if key >= len(self.children): raise KeyError(unwrap( ''' No field numbered %s is present in this %s ''', key, type_name(self) )) try: return self._lazy_child(key) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e def __setitem__(self, key, value): """ Allows settings fields by name or index :param key: A unicode string of the field name, or an integer of the field index :param value: A native Python datatype to set the field value to. This method will construct the appropriate Asn1Value object from _fields. :raises: ValueError - when a field name or index is invalid """ # We inline this check to prevent method invocation each time if self.children is None: self._parse_children() if not isinstance(key, int_types): if key not in self._field_map: raise KeyError(unwrap( ''' No field named "%s" defined for %s ''', key, type_name(self) )) key = self._field_map[key] field_name, field_spec, value_spec, field_params, _ = self._determine_spec(key) new_value = self._make_value(field_name, field_spec, value_spec, field_params, value) invalid_value = False if isinstance(new_value, Any): invalid_value = new_value.parsed is None else: invalid_value = new_value.contents is None if invalid_value: raise ValueError(unwrap( ''' Value for field "%s" of %s is not set ''', field_name, type_name(self) )) self.children[key] = new_value if self._native is not None: self._native[self._fields[key][0]] = self.children[key].native self._mutated = True def __delitem__(self, key): """ Allows deleting optional or default fields by name or index :param key: A unicode string of the field name, or an integer of the field index :raises: ValueError - when a field name or index is invalid, or the field is not optional or defaulted """ # We inline this check to prevent method invocation each time if self.children is None: self._parse_children() if not isinstance(key, int_types): if key not in self._field_map: raise KeyError(unwrap( ''' No field named "%s" defined for %s ''', key, type_name(self) )) key = self._field_map[key] name, _, params = self._fields[key] if not params or ('default' not in params and 'optional' not in params): raise ValueError(unwrap( ''' Can not delete the value for the field "%s" of %s since it is not optional or defaulted ''', name, type_name(self) )) if 'optional' in params: self.children[key] = VOID if self._native is not None: self._native[name] = None else: self.__setitem__(key, None) self._mutated = True def __iter__(self): """ :return: An iterator of field key names """ for info in self._fields: yield info[0] def _set_contents(self, force=False): """ Updates the .contents attribute of the value with the encoded value of all of the child objects :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() contents = BytesIO() for index, info in enumerate(self._fields): child = self.children[index] if child is None: child_dump = b'' elif child.__class__ == tuple: if force: child_dump = self._lazy_child(index).dump(force=force) else: child_dump = child[3] + child[4] + child[5] else: child_dump = child.dump(force=force) # Skip values that are the same as the default if info[2] and 'default' in info[2]: default_value = info[1](**info[2]) if default_value.dump() == child_dump: continue contents.write(child_dump) self._contents = contents.getvalue() self._header = None if self._trailer != b'': self._trailer = b'' def _setup(self): """ Generates _field_map, _field_ids and _oid_nums for use in parsing """ cls = self.__class__ cls._field_map = {} cls._field_ids = [] cls._precomputed_specs = [] for index, field in enumerate(cls._fields): if len(field) < 3: field = field + ({},) cls._fields[index] = field cls._field_map[field[0]] = index cls._field_ids.append(_build_id_tuple(field[2], field[1])) if cls._oid_pair is not None: cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]]) for index, field in enumerate(cls._fields): has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index if has_callback or is_mapped_oid: cls._precomputed_specs.append(None) else: cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None)) def _determine_spec(self, index): """ Determine how a value for a field should be constructed :param index: The field number :return: A tuple containing the following elements: - unicode string of the field name - Asn1Value class of the field spec - Asn1Value class of the value spec - None or dict of params to pass to the field spec - None or Asn1Value class indicating the value spec was derived from an OID or a spec callback """ name, field_spec, field_params = self._fields[index] value_spec = field_spec spec_override = None if self._spec_callbacks is not None and name in self._spec_callbacks: callback = self._spec_callbacks[name] spec_override = callback(self) if spec_override: # Allow a spec callback to specify both the base spec and # the override, for situations such as OctetString and parse_as if spec_override.__class__ == tuple and len(spec_override) == 2: field_spec, value_spec = spec_override if value_spec is None: value_spec = field_spec spec_override = None # When no field spec is specified, use a single return value as that elif field_spec is None: field_spec = spec_override value_spec = field_spec spec_override = None else: value_spec = spec_override elif self._oid_nums is not None and self._oid_nums[1] == index: oid = self._lazy_child(self._oid_nums[0]).native if oid in self._oid_specs: spec_override = self._oid_specs[oid] value_spec = spec_override return (name, field_spec, value_spec, field_params, spec_override) def _make_value(self, field_name, field_spec, value_spec, field_params, value): """ Contructs an appropriate Asn1Value object for a field :param field_name: A unicode string of the field name :param field_spec: An Asn1Value class that is the field spec :param value_spec: An Asn1Value class that is the vaue spec :param field_params: None or a dict of params for the field spec :param value: The value to construct an Asn1Value object from :return: An instance of a child class of Asn1Value """ if value is None and 'optional' in field_params: return VOID specs_different = field_spec != value_spec is_any = issubclass(field_spec, Any) if issubclass(value_spec, Choice): is_asn1value = isinstance(value, Asn1Value) is_tuple = isinstance(value, tuple) and len(value) == 2 is_dict = isinstance(value, dict) and len(value) == 1 if not is_asn1value and not is_tuple and not is_dict: raise ValueError(unwrap( ''' Can not set a native python value to %s, which has the choice type of %s - value must be an instance of Asn1Value ''', field_name, type_name(value_spec) )) if is_tuple or is_dict: value = value_spec(value) if not isinstance(value, value_spec): wrapper = value_spec() wrapper.validate(value.class_, value.tag, value.contents) wrapper._parsed = value new_value = wrapper else: new_value = value elif isinstance(value, field_spec): new_value = value if specs_different: new_value.parse(value_spec) elif (not specs_different or is_any) and not isinstance(value, value_spec): if (not is_any or specs_different) and isinstance(value, Asn1Value): raise TypeError(unwrap( ''' %s value must be %s, not %s ''', field_name, type_name(value_spec), type_name(value) )) new_value = value_spec(value, **field_params) else: if isinstance(value, value_spec): new_value = value else: if isinstance(value, Asn1Value): raise TypeError(unwrap( ''' %s value must be %s, not %s ''', field_name, type_name(value_spec), type_name(value) )) new_value = value_spec(value) # For when the field is OctetString or OctetBitString with embedded # values we need to wrap the value in the field spec to get the # appropriate encoded value. if specs_different and not is_any: wrapper = field_spec(value=new_value.dump(), **field_params) wrapper._parsed = (new_value, new_value.__class__, None) new_value = wrapper new_value = _fix_tagging(new_value, field_params) return new_value def _parse_children(self, recurse=False): """ Parses the contents and generates Asn1Value objects based on the definitions from _fields. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects """ cls = self.__class__ if self._contents is None: if self._fields: self.children = [VOID] * len(self._fields) for index, (_, _, params) in enumerate(self._fields): if 'default' in params: if cls._precomputed_specs[index]: field_name, field_spec, value_spec, field_params, _ = cls._precomputed_specs[index] else: field_name, field_spec, value_spec, field_params, _ = self._determine_spec(index) self.children[index] = self._make_value(field_name, field_spec, value_spec, field_params, None) return try: self.children = [] contents_length = len(self._contents) child_pointer = 0 field = 0 field_len = len(self._fields) parts = None again = child_pointer < contents_length while again: if parts is None: parts, child_pointer = _parse(self._contents, contents_length, pointer=child_pointer) again = child_pointer < contents_length if field < field_len: _, field_spec, value_spec, field_params, spec_override = ( cls._precomputed_specs[field] or self._determine_spec(field)) # If the next value is optional or default, allow it to be absent if field_params and ('optional' in field_params or 'default' in field_params): if self._field_ids[field] != (parts[0], parts[2]) and field_spec != Any: # See if the value is a valid choice before assuming # that we have a missing optional or default value choice_match = False if issubclass(field_spec, Choice): try: tester = field_spec(**field_params) tester.validate(parts[0], parts[2], parts[4]) choice_match = True except (ValueError): pass if not choice_match: if 'optional' in field_params: self.children.append(VOID) else: self.children.append(field_spec(**field_params)) field += 1 again = True continue if field_spec is None or (spec_override and issubclass(field_spec, Any)): field_spec = value_spec spec_override = None if spec_override: child = parts + (field_spec, field_params, value_spec) else: child = parts + (field_spec, field_params) # Handle situations where an optional or defaulted field definition is incorrect elif field_len > 0 and field + 1 <= field_len: missed_fields = [] prev_field = field - 1 while prev_field >= 0: prev_field_info = self._fields[prev_field] if len(prev_field_info) < 3: break if 'optional' in prev_field_info[2] or 'default' in prev_field_info[2]: missed_fields.append(prev_field_info[0]) prev_field -= 1 plural = 's' if len(missed_fields) > 1 else '' missed_field_names = ', '.join(missed_fields) raise ValueError(unwrap( ''' Data for field %s (%s class, %s method, tag %s) does not match the field definition%s of %s ''', field + 1, CLASS_NUM_TO_NAME_MAP.get(parts[0]), METHOD_NUM_TO_NAME_MAP.get(parts[1]), parts[2], plural, missed_field_names )) else: child = parts if recurse: child = _build(*child) if isinstance(child, (Sequence, SequenceOf)): child._parse_children(recurse=True) self.children.append(child) field += 1 parts = None index = len(self.children) while index < field_len: name, field_spec, field_params = self._fields[index] if 'default' in field_params: self.children.append(field_spec(**field_params)) elif 'optional' in field_params: self.children.append(VOID) else: raise ValueError(unwrap( ''' Field "%s" is missing from structure ''', name )) index += 1 except (ValueError, TypeError) as e: self.children = None args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e def spec(self, field_name): """ Determines the spec to use for the field specified. Depending on how the spec is determined (_oid_pair or _spec_callbacks), it may be necessary to set preceding field values before calling this. Usually specs, if dynamic, are controlled by a preceding ObjectIdentifier field. :param field_name: A unicode string of the field name to get the spec for :return: A child class of asn1crypto.core.Asn1Value that the field must be encoded using """ if not isinstance(field_name, str_cls): raise TypeError(unwrap( ''' field_name must be a unicode string, not %s ''', type_name(field_name) )) if self._fields is None: raise ValueError(unwrap( ''' Unable to retrieve spec for field %s in the class %s because _fields has not been set ''', repr(field_name), type_name(self) )) index = self._field_map[field_name] info = self._determine_spec(index) return info[2] @property def native(self): """ The native Python datatype representation of this value :return: An OrderedDict or None. If an OrderedDict, all child values are recursively converted to native representation also. """ if self.contents is None: return None if self._native is None: if self.children is None: self._parse_children(recurse=True) try: self._native = OrderedDict() for index, child in enumerate(self.children): if child.__class__ == tuple: child = _build(*child) self.children[index] = child try: name = self._fields[index][0] except (IndexError): name = str_cls(index) self._native[name] = child.native except (ValueError, TypeError) as e: self._native = None args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e return self._native def _copy(self, other, copy_func): """ Copies the contents of another Sequence object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Sequence, self)._copy(other, copy_func) if self.children is not None: self.children = [] for child in other.children: if child.__class__ == tuple: self.children.append(child) else: self.children.append(child.copy()) def debug(self, nest_level=1): """ Show the binary data and parsed data in a tree structure """ if self.children is None: self._parse_children() prefix = ' ' * nest_level _basic_debug(prefix, self) for field_name in self: child = self._lazy_child(self._field_map[field_name]) if child is not VOID: print('%s Field "%s"' % (prefix, field_name)) child.debug(nest_level + 3) def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ # If the length is indefinite, force the re-encoding if self._header is not None and self._header[-1:] == b'\x80': force = True # We can't force encoding if we don't have a spec if force and self._fields == [] and self.__class__ is Sequence: force = False if force: self._set_contents(force=force) if self._fields and self.children is not None: for index, (field_name, _, params) in enumerate(self._fields): if self.children[index] is not VOID: continue if 'default' in params or 'optional' in params: continue raise ValueError(unwrap( ''' Field "%s" is missing from structure ''', field_name )) return Asn1Value.dump(self) class SequenceOf(Asn1Value): """ Represents a sequence (ordered) of a single type of values from ASN.1 as a Python object with a list-like interface """ tag = 16 class_ = 0 method = 1 # A list of child objects children = None # SequenceOf overrides .contents to be a property so that the mutated state # of child objects can be checked to ensure everything is up-to-date _contents = None # Variable to track if the object has been mutated _mutated = False # An Asn1Value class to use when parsing children _child_spec = None def __init__(self, value=None, default=None, contents=None, spec=None, **kwargs): """ Allows setting child objects and the _child_spec via the spec parameter before passing everything else along to Asn1Value.__init__() :param value: A native Python datatype to initialize the object value with :param default: The default value if no value is specified :param contents: A byte string of the encoded contents of the value :param spec: A class derived from Asn1Value to use to parse children """ if spec: self._child_spec = spec Asn1Value.__init__(self, **kwargs) try: if contents is not None: self.contents = contents else: if value is None and default is not None: value = default if value is not None: for index, child in enumerate(value): self.__setitem__(index, child) # Make sure a blank list is serialized if self.contents is None: self._set_contents() except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while constructing %s' % type_name(self),) + args raise e @property def contents(self): """ :return: A byte string of the DER-encoded contents of the sequence """ if self.children is None: return self._contents if self._is_mutated(): self._set_contents() return self._contents @contents.setter def contents(self, value): """ :param value: A byte string of the DER-encoded contents of the sequence """ self._contents = value def _is_mutated(self): """ :return: A boolean - if the sequence or any children (recursively) have been mutated """ mutated = self._mutated if self.children is not None: for child in self.children: if isinstance(child, Sequence) or isinstance(child, SequenceOf): mutated = mutated or child._is_mutated() return mutated def _lazy_child(self, index): """ Builds a child object if the child has only been parsed into a tuple so far """ child = self.children[index] if child.__class__ == tuple: child = _build(*child) self.children[index] = child return child def _make_value(self, value): """ Constructs a _child_spec value from a native Python data type, or an appropriate Asn1Value object :param value: A native Python value, or some child of Asn1Value :return: An object of type _child_spec """ if isinstance(value, self._child_spec): new_value = value elif issubclass(self._child_spec, Any): if isinstance(value, Asn1Value): new_value = value else: raise ValueError(unwrap( ''' Can not set a native python value to %s where the _child_spec is Any - value must be an instance of Asn1Value ''', type_name(self) )) elif issubclass(self._child_spec, Choice): if not isinstance(value, Asn1Value): raise ValueError(unwrap( ''' Can not set a native python value to %s where the _child_spec is the choice type %s - value must be an instance of Asn1Value ''', type_name(self), self._child_spec.__name__ )) if not isinstance(value, self._child_spec): wrapper = self._child_spec() wrapper.validate(value.class_, value.tag, value.contents) wrapper._parsed = value value = wrapper new_value = value else: return self._child_spec(value=value) params = {} if self._child_spec.explicit: params['explicit'] = self._child_spec.explicit if self._child_spec.implicit: params['implicit'] = (self._child_spec.class_, self._child_spec.tag) return _fix_tagging(new_value, params) def __len__(self): """ :return: An integer """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() return len(self.children) def __getitem__(self, key): """ Allows accessing children via index :param key: Integer index of child """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() return self._lazy_child(key) def __setitem__(self, key, value): """ Allows overriding a child via index :param key: Integer index of child :param value: Native python datatype that will be passed to _child_spec to create new child object """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() new_value = self._make_value(value) # If adding at the end, create a space for the new value if key == len(self.children): self.children.append(None) if self._native is not None: self._native.append(None) self.children[key] = new_value if self._native is not None: self._native[key] = self.children[key].native self._mutated = True def __delitem__(self, key): """ Allows removing a child via index :param key: Integer index of child """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() self.children.pop(key) if self._native is not None: self._native.pop(key) self._mutated = True def __iter__(self): """ :return: An iter() of child objects """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() for index in range(0, len(self.children)): yield self._lazy_child(index) def __contains__(self, item): """ :param item: An object of the type cls._child_spec :return: A boolean if the item is contained in this SequenceOf """ if item is None or item is VOID: return False if not isinstance(item, self._child_spec): raise TypeError(unwrap( ''' Checking membership in %s is only available for instances of %s, not %s ''', type_name(self), type_name(self._child_spec), type_name(item) )) for child in self: if child == item: return True return False def append(self, value): """ Allows adding a child to the end of the sequence :param value: Native python datatype that will be passed to _child_spec to create new child object """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() self.children.append(self._make_value(value)) if self._native is not None: self._native.append(self.children[-1].native) self._mutated = True def _set_contents(self, force=False): """ Encodes all child objects into the contents for this object :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() contents = BytesIO() for child in self: contents.write(child.dump(force=force)) self._contents = contents.getvalue() self._header = None if self._trailer != b'': self._trailer = b'' def _parse_children(self, recurse=False): """ Parses the contents and generates Asn1Value objects based on the definitions from _child_spec. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects """ try: self.children = [] if self._contents is None: return contents_length = len(self._contents) child_pointer = 0 while child_pointer < contents_length: parts, child_pointer = _parse(self._contents, contents_length, pointer=child_pointer) if self._child_spec: child = parts + (self._child_spec,) else: child = parts if recurse: child = _build(*child) if isinstance(child, (Sequence, SequenceOf)): child._parse_children(recurse=True) self.children.append(child) except (ValueError, TypeError) as e: self.children = None args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e def spec(self): """ Determines the spec to use for child values. :return: A child class of asn1crypto.core.Asn1Value that child values must be encoded using """ return self._child_spec @property def native(self): """ The native Python datatype representation of this value :return: A list or None. If a list, all child values are recursively converted to native representation also. """ if self.contents is None: return None if self._native is None: if self.children is None: self._parse_children(recurse=True) try: self._native = [child.native for child in self] except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e return self._native def _copy(self, other, copy_func): """ Copies the contents of another SequenceOf object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(SequenceOf, self)._copy(other, copy_func) if self.children is not None: self.children = [] for child in other.children: if child.__class__ == tuple: self.children.append(child) else: self.children.append(child.copy()) def debug(self, nest_level=1): """ Show the binary data and parsed data in a tree structure """ if self.children is None: self._parse_children() prefix = ' ' * nest_level _basic_debug(prefix, self) for child in self: child.debug(nest_level + 1) def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value """ # If the length is indefinite, force the re-encoding if self._header is not None and self._header[-1:] == b'\x80': force = True if force: self._set_contents(force=force) return Asn1Value.dump(self) class Set(Sequence): """ Represents a set of fields (unordered) from ASN.1 as a Python object with a dict-like interface """ method = 1 class_ = 0 tag = 17 # A dict of 2-element tuples in the form (class_, tag) as keys and integers # as values that are the index of the field in _fields _field_ids = None def _setup(self): """ Generates _field_map, _field_ids and _oid_nums for use in parsing """ cls = self.__class__ cls._field_map = {} cls._field_ids = {} cls._precomputed_specs = [] for index, field in enumerate(cls._fields): if len(field) < 3: field = field + ({},) cls._fields[index] = field cls._field_map[field[0]] = index cls._field_ids[_build_id_tuple(field[2], field[1])] = index if cls._oid_pair is not None: cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]]) for index, field in enumerate(cls._fields): has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index if has_callback or is_mapped_oid: cls._precomputed_specs.append(None) else: cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None)) def _parse_children(self, recurse=False): """ Parses the contents and generates Asn1Value objects based on the definitions from _fields. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects """ cls = self.__class__ if self._contents is None: if self._fields: self.children = [VOID] * len(self._fields) for index, (_, _, params) in enumerate(self._fields): if 'default' in params: if cls._precomputed_specs[index]: field_name, field_spec, value_spec, field_params, _ = cls._precomputed_specs[index] else: field_name, field_spec, value_spec, field_params, _ = self._determine_spec(index) self.children[index] = self._make_value(field_name, field_spec, value_spec, field_params, None) return try: child_map = {} contents_length = len(self.contents) child_pointer = 0 seen_field = 0 while child_pointer < contents_length: parts, child_pointer = _parse(self.contents, contents_length, pointer=child_pointer) id_ = (parts[0], parts[2]) field = self._field_ids.get(id_) if field is None: raise ValueError(unwrap( ''' Data for field %s (%s class, %s method, tag %s) does not match any of the field definitions ''', seen_field, CLASS_NUM_TO_NAME_MAP.get(parts[0]), METHOD_NUM_TO_NAME_MAP.get(parts[1]), parts[2], )) _, field_spec, value_spec, field_params, spec_override = ( cls._precomputed_specs[field] or self._determine_spec(field)) if field_spec is None or (spec_override and issubclass(field_spec, Any)): field_spec = value_spec spec_override = None if spec_override: child = parts + (field_spec, field_params, value_spec) else: child = parts + (field_spec, field_params) if recurse: child = _build(*child) if isinstance(child, (Sequence, SequenceOf)): child._parse_children(recurse=True) child_map[field] = child seen_field += 1 total_fields = len(self._fields) for index in range(0, total_fields): if index in child_map: continue name, field_spec, value_spec, field_params, spec_override = ( cls._precomputed_specs[index] or self._determine_spec(index)) if field_spec is None or (spec_override and issubclass(field_spec, Any)): field_spec = value_spec spec_override = None missing = False if not field_params: missing = True elif 'optional' not in field_params and 'default' not in field_params: missing = True elif 'optional' in field_params: child_map[index] = VOID elif 'default' in field_params: child_map[index] = field_spec(**field_params) if missing: raise ValueError(unwrap( ''' Missing required field "%s" from %s ''', name, type_name(self) )) self.children = [] for index in range(0, total_fields): self.children.append(child_map[index]) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e def _set_contents(self, force=False): """ Encodes all child objects into the contents for this object. This method is overridden because a Set needs to be encoded by removing defaulted fields and then sorting the fields by tag. :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() child_tag_encodings = [] for index, child in enumerate(self.children): child_encoding = child.dump(force=force) # Skip encoding defaulted children name, spec, field_params = self._fields[index] if 'default' in field_params: if spec(**field_params).dump() == child_encoding: continue child_tag_encodings.append((child.tag, child_encoding)) child_tag_encodings.sort(key=lambda ct: ct[0]) self._contents = b''.join([ct[1] for ct in child_tag_encodings]) self._header = None if self._trailer != b'': self._trailer = b'' class SetOf(SequenceOf): """ Represents a set (unordered) of a single type of values from ASN.1 as a Python object with a list-like interface """ tag = 17 def _set_contents(self, force=False): """ Encodes all child objects into the contents for this object. This method is overridden because a SetOf needs to be encoded by sorting the child encodings. :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() child_encodings = [] for child in self: child_encodings.append(child.dump(force=force)) self._contents = b''.join(sorted(child_encodings)) self._header = None if self._trailer != b'': self._trailer = b'' class EmbeddedPdv(Sequence): """ A sequence structure """ tag = 11 class NumericString(AbstractString): """ Represents a numeric string from ASN.1 as a Python unicode string """ tag = 18 _encoding = 'latin1' class PrintableString(AbstractString): """ Represents a printable string from ASN.1 as a Python unicode string """ tag = 19 _encoding = 'latin1' class TeletexString(AbstractString): """ Represents a teletex string from ASN.1 as a Python unicode string """ tag = 20 _encoding = 'teletex' class VideotexString(OctetString): """ Represents a videotex string from ASN.1 as a Python byte string """ tag = 21 class IA5String(AbstractString): """ Represents an IA5 string from ASN.1 as a Python unicode string """ tag = 22 _encoding = 'ascii' class AbstractTime(AbstractString): """ Represents a time from ASN.1 as a Python datetime.datetime object """ @property def _parsed_time(self): """ The parsed datetime string. :raises: ValueError - when an invalid value is passed :return: A dict with the parsed values """ string = str_cls(self) m = self._TIMESTRING_RE.match(string) if not m: raise ValueError(unwrap( ''' Error parsing %s to a %s ''', string, type_name(self), )) groups = m.groupdict() tz = None if groups['zulu']: tz = timezone.utc elif groups['dsign']: sign = 1 if groups['dsign'] == '+' else -1 tz = create_timezone(sign * timedelta( hours=int(groups['dhour']), minutes=int(groups['dminute'] or 0) )) if groups['fraction']: # Compute fraction in microseconds fract = Fraction( int(groups['fraction']), 10 ** len(groups['fraction']) ) * 1000000 if groups['minute'] is None: fract *= 3600 elif groups['second'] is None: fract *= 60 fract_usec = int(fract.limit_denominator(1)) else: fract_usec = 0 return { 'year': int(groups['year']), 'month': int(groups['month']), 'day': int(groups['day']), 'hour': int(groups['hour']), 'minute': int(groups['minute'] or 0), 'second': int(groups['second'] or 0), 'tzinfo': tz, 'fraction': fract_usec, } @property def native(self): """ The native Python datatype representation of this value :return: A datetime.datetime object, asn1crypto.util.extended_datetime object or None. The datetime object is usually timezone aware. If it's naive, then it's in the sender's local time; see X.680 sect. 42.3 """ if self.contents is None: return None if self._native is None: parsed = self._parsed_time fraction = parsed.pop('fraction', 0) value = self._get_datetime(parsed) if fraction: value += timedelta(microseconds=fraction) self._native = value return self._native class UTCTime(AbstractTime): """ Represents a UTC time from ASN.1 as a timezone aware Python datetime.datetime object """ tag = 23 # Regular expression for UTCTime as described in X.680 sect. 43 and ISO 8601 _TIMESTRING_RE = re.compile(r''' ^ # YYMMDD (?P<year>\d{2}) (?P<month>\d{2}) (?P<day>\d{2}) # hhmm or hhmmss (?P<hour>\d{2}) (?P<minute>\d{2}) (?P<second>\d{2})? # Matches nothing, needed because GeneralizedTime uses this. (?P<fraction>) # Z or [-+]hhmm (?: (?P<zulu>Z) | (?: (?P<dsign>[-+]) (?P<dhour>\d{2}) (?P<dminute>\d{2}) ) ) $ ''', re.X) def set(self, value): """ Sets the value of the object :param value: A unicode string or a datetime.datetime object :raises: ValueError - when an invalid value is passed """ if isinstance(value, datetime): if not value.tzinfo: raise ValueError('Must be timezone aware') # Convert value to UTC. value = value.astimezone(utc_with_dst) if not 1950 <= value.year <= 2049: raise ValueError('Year of the UTCTime is not in range [1950, 2049], use GeneralizedTime instead') value = value.strftime('%y%m%d%H%M%SZ') if _PY2: value = value.decode('ascii') AbstractString.set(self, value) # Set it to None and let the class take care of converting the next # time that .native is called self._native = None def _get_datetime(self, parsed): """ Create a datetime object from the parsed time. :return: An aware datetime.datetime object """ # X.680 only specifies that UTCTime is not using a century. # So "18" could as well mean 2118 or 1318. # X.509 and CMS specify to use UTCTime for years earlier than 2050. # Assume that UTCTime is only used for years [1950, 2049]. if parsed['year'] < 50: parsed['year'] += 2000 else: parsed['year'] += 1900 return datetime(**parsed) class GeneralizedTime(AbstractTime): """ Represents a generalized time from ASN.1 as a Python datetime.datetime object or asn1crypto.util.extended_datetime object in UTC """ tag = 24 # Regular expression for GeneralizedTime as described in X.680 sect. 42 and ISO 8601 _TIMESTRING_RE = re.compile(r''' ^ # YYYYMMDD (?P<year>\d{4}) (?P<month>\d{2}) (?P<day>\d{2}) # hh or hhmm or hhmmss (?P<hour>\d{2}) (?: (?P<minute>\d{2}) (?P<second>\d{2})? )? # Optional fraction; [.,]dddd (one or more decimals) # If Seconds are given, it's fractions of Seconds. # Else if Minutes are given, it's fractions of Minutes. # Else it's fractions of Hours. (?: [,.] (?P<fraction>\d+) )? # Optional timezone. If left out, the time is in local time. # Z or [-+]hh or [-+]hhmm (?: (?P<zulu>Z) | (?: (?P<dsign>[-+]) (?P<dhour>\d{2}) (?P<dminute>\d{2})? ) )? $ ''', re.X) def set(self, value): """ Sets the value of the object :param value: A unicode string, a datetime.datetime object or an asn1crypto.util.extended_datetime object :raises: ValueError - when an invalid value is passed """ if isinstance(value, (datetime, extended_datetime)): if not value.tzinfo: raise ValueError('Must be timezone aware') # Convert value to UTC. value = value.astimezone(utc_with_dst) if value.microsecond: fraction = '.' + str(value.microsecond).zfill(6).rstrip('0') else: fraction = '' value = value.strftime('%Y%m%d%H%M%S') + fraction + 'Z' if _PY2: value = value.decode('ascii') AbstractString.set(self, value) # Set it to None and let the class take care of converting the next # time that .native is called self._native = None def _get_datetime(self, parsed): """ Create a datetime object from the parsed time. :return: A datetime.datetime object or asn1crypto.util.extended_datetime object. It may or may not be aware. """ if parsed['year'] == 0: # datetime does not support year 0. Use extended_datetime instead. return extended_datetime(**parsed) else: return datetime(**parsed) class GraphicString(AbstractString): """ Represents a graphic string from ASN.1 as a Python unicode string """ tag = 25 # This is technically not correct since this type can contain any charset _encoding = 'latin1' class VisibleString(AbstractString): """ Represents a visible string from ASN.1 as a Python unicode string """ tag = 26 _encoding = 'latin1' class GeneralString(AbstractString): """ Represents a general string from ASN.1 as a Python unicode string """ tag = 27 # This is technically not correct since this type can contain any charset _encoding = 'latin1' class UniversalString(AbstractString): """ Represents a universal string from ASN.1 as a Python unicode string """ tag = 28 _encoding = 'utf-32-be' class CharacterString(AbstractString): """ Represents a character string from ASN.1 as a Python unicode string """ tag = 29 # This is technically not correct since this type can contain any charset _encoding = 'latin1' class BMPString(AbstractString): """ Represents a BMP string from ASN.1 as a Python unicode string """ tag = 30 _encoding = 'utf-16-be' def _basic_debug(prefix, self): """ Prints out basic information about an Asn1Value object. Extracted for reuse among different classes that customize the debug information. :param prefix: A unicode string of spaces to prefix output line with :param self: The object to print the debugging information about """ print('%s%s Object #%s' % (prefix, type_name(self), id(self))) if self._header: print('%s Header: 0x%s' % (prefix, binascii.hexlify(self._header or b'').decode('utf-8'))) has_header = self.method is not None and self.class_ is not None and self.tag is not None if has_header: method_name = METHOD_NUM_TO_NAME_MAP.get(self.method) class_name = CLASS_NUM_TO_NAME_MAP.get(self.class_) if self.explicit is not None: for class_, tag in self.explicit: print( '%s %s tag %s (explicitly tagged)' % ( prefix, CLASS_NUM_TO_NAME_MAP.get(class_), tag ) ) if has_header: print('%s %s %s %s' % (prefix, method_name, class_name, self.tag)) elif self.implicit: if has_header: print('%s %s %s tag %s (implicitly tagged)' % (prefix, method_name, class_name, self.tag)) elif has_header: print('%s %s %s tag %s' % (prefix, method_name, class_name, self.tag)) if self._trailer: print('%s Trailer: 0x%s' % (prefix, binascii.hexlify(self._trailer or b'').decode('utf-8'))) print('%s Data: 0x%s' % (prefix, binascii.hexlify(self.contents or b'').decode('utf-8'))) def _tag_type_to_explicit_implicit(params): """ Converts old-style "tag_type" and "tag" params to "explicit" and "implicit" :param params: A dict of parameters to convert from tag_type/tag to explicit/implicit """ if 'tag_type' in params: if params['tag_type'] == 'explicit': params['explicit'] = (params.get('class', 2), params['tag']) elif params['tag_type'] == 'implicit': params['implicit'] = (params.get('class', 2), params['tag']) del params['tag_type'] del params['tag'] if 'class' in params: del params['class'] def _fix_tagging(value, params): """ Checks if a value is properly tagged based on the spec, and re/untags as necessary :param value: An Asn1Value object :param params: A dict of spec params :return: An Asn1Value that is properly tagged """ _tag_type_to_explicit_implicit(params) retag = False if 'implicit' not in params: if value.implicit is not False: retag = True else: if isinstance(params['implicit'], tuple): class_, tag = params['implicit'] else: tag = params['implicit'] class_ = 'context' if value.implicit is False: retag = True elif value.class_ != CLASS_NAME_TO_NUM_MAP[class_] or value.tag != tag: retag = True if params.get('explicit') != value.explicit: retag = True if retag: return value.retag(params) return value def _build_id_tuple(params, spec): """ Builds a 2-element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it :param params: A dict of params to pass to spec :param spec: An Asn1Value class :return: A 2-element integer tuple in the form (class_, tag) """ # Handle situations where the spec is not known at setup time if spec is None: return (None, None) required_class = spec.class_ required_tag = spec.tag _tag_type_to_explicit_implicit(params) if 'explicit' in params: if isinstance(params['explicit'], tuple): required_class, required_tag = params['explicit'] else: required_class = 2 required_tag = params['explicit'] elif 'implicit' in params: if isinstance(params['implicit'], tuple): required_class, required_tag = params['implicit'] else: required_class = 2 required_tag = params['implicit'] if required_class is not None and not isinstance(required_class, int_types): required_class = CLASS_NAME_TO_NUM_MAP[required_class] required_class = params.get('class_', required_class) required_tag = params.get('tag', required_tag) return (required_class, required_tag) def _int_to_bit_tuple(value, bits): """ Format value as a tuple of 1s and 0s. :param value: A non-negative integer to format :param bits: Number of bits in the output :return: A tuple of 1s and 0s with bits members. """ if not value and not bits: return () result = tuple(map(int, format(value, '0{0}b'.format(bits)))) if len(result) != bits: raise ValueError('Result too large: {0} > {1}'.format(len(result), bits)) return result _UNIVERSAL_SPECS = { 1: Boolean, 2: Integer, 3: BitString, 4: OctetString, 5: Null, 6: ObjectIdentifier, 7: ObjectDescriptor, 8: InstanceOf, 9: Real, 10: Enumerated, 11: EmbeddedPdv, 12: UTF8String, 13: RelativeOid, 16: Sequence, 17: Set, 18: NumericString, 19: PrintableString, 20: TeletexString, 21: VideotexString, 22: IA5String, 23: UTCTime, 24: GeneralizedTime, 25: GraphicString, 26: VisibleString, 27: GeneralString, 28: UniversalString, 29: CharacterString, 30: BMPString } def _build(class_, method, tag, header, contents, trailer, spec=None, spec_params=None, nested_spec=None): """ Builds an Asn1Value object generically, or using a spec with optional params :param class_: An integer representing the ASN.1 class :param method: An integer representing the ASN.1 method :param tag: An integer representing the ASN.1 tag :param header: A byte string of the ASN.1 header (class, method, tag, length) :param contents: A byte string of the ASN.1 value :param trailer: A byte string of any ASN.1 trailer (only used by indefinite length encodings) :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param nested_spec: For certain Asn1Value classes (such as OctetString and BitString), the contents can be further parsed and interpreted as another Asn1Value. This parameter controls the spec for that sub-parsing. :return: An object of the type spec, or if not specified, a child of Asn1Value """ if spec_params is not None: _tag_type_to_explicit_implicit(spec_params) if header is None: return VOID header_set = False # If an explicit specification was passed in, make sure it matches if spec is not None: # If there is explicit tagging and contents, we have to split # the header and trailer off before we do the parsing no_explicit = spec_params and 'no_explicit' in spec_params if not no_explicit and (spec.explicit or (spec_params and 'explicit' in spec_params)): if spec_params: value = spec(**spec_params) else: value = spec() original_explicit = value.explicit explicit_info = reversed(original_explicit) parsed_class = class_ parsed_method = method parsed_tag = tag to_parse = contents explicit_header = header explicit_trailer = trailer or b'' for expected_class, expected_tag in explicit_info: if parsed_class != expected_class: raise ValueError(unwrap( ''' Error parsing %s - explicitly-tagged class should have been %s, but %s was found ''', type_name(value), CLASS_NUM_TO_NAME_MAP.get(expected_class), CLASS_NUM_TO_NAME_MAP.get(parsed_class, parsed_class) )) if parsed_method != 1: raise ValueError(unwrap( ''' Error parsing %s - explicitly-tagged method should have been %s, but %s was found ''', type_name(value), METHOD_NUM_TO_NAME_MAP.get(1), METHOD_NUM_TO_NAME_MAP.get(parsed_method, parsed_method) )) if parsed_tag != expected_tag: raise ValueError(unwrap( ''' Error parsing %s - explicitly-tagged tag should have been %s, but %s was found ''', type_name(value), expected_tag, parsed_tag )) info, _ = _parse(to_parse, len(to_parse)) parsed_class, parsed_method, parsed_tag, parsed_header, to_parse, parsed_trailer = info if not isinstance(value, Choice): explicit_header += parsed_header explicit_trailer = parsed_trailer + explicit_trailer value = _build(*info, spec=spec, spec_params={'no_explicit': True}) value._header = explicit_header value._trailer = explicit_trailer value.explicit = original_explicit header_set = True else: if spec_params: value = spec(contents=contents, **spec_params) else: value = spec(contents=contents) if spec is Any: pass elif isinstance(value, Choice): value.validate(class_, tag, contents) try: # Force parsing the Choice now value.contents = header + value.contents header = b'' value.parse() except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(value),) + args raise e else: if class_ != value.class_: raise ValueError(unwrap( ''' Error parsing %s - class should have been %s, but %s was found ''', type_name(value), CLASS_NUM_TO_NAME_MAP.get(value.class_), CLASS_NUM_TO_NAME_MAP.get(class_, class_) )) if method != value.method: # Allow parsing a primitive method as constructed if the value # is indefinite length. This is to allow parsing BER. ber_indef = method == 1 and value.method == 0 and trailer == b'\x00\x00' if not ber_indef or not isinstance(value, Constructable): raise ValueError(unwrap( ''' Error parsing %s - method should have been %s, but %s was found ''', type_name(value), METHOD_NUM_TO_NAME_MAP.get(value.method), METHOD_NUM_TO_NAME_MAP.get(method, method) )) else: value.method = method value._indefinite = True if tag != value.tag: if isinstance(value._bad_tag, tuple): is_bad_tag = tag in value._bad_tag else: is_bad_tag = tag == value._bad_tag if not is_bad_tag: raise ValueError(unwrap( ''' Error parsing %s - tag should have been %s, but %s was found ''', type_name(value), value.tag, tag )) # For explicitly tagged, un-speced parsings, we use a generic container # since we will be parsing the contents and discarding the outer object # anyway a little further on elif spec_params and 'explicit' in spec_params: original_value = Asn1Value(contents=contents, **spec_params) original_explicit = original_value.explicit to_parse = contents explicit_header = header explicit_trailer = trailer or b'' for expected_class, expected_tag in reversed(original_explicit): info, _ = _parse(to_parse, len(to_parse)) _, _, _, parsed_header, to_parse, parsed_trailer = info explicit_header += parsed_header explicit_trailer = parsed_trailer + explicit_trailer value = _build(*info, spec=spec, spec_params={'no_explicit': True}) value._header = header + value._header value._trailer += trailer or b'' value.explicit = original_explicit header_set = True # If no spec was specified, allow anything and just process what # is in the input data else: if tag not in _UNIVERSAL_SPECS: raise ValueError(unwrap( ''' Unknown element - %s class, %s method, tag %s ''', CLASS_NUM_TO_NAME_MAP.get(class_), METHOD_NUM_TO_NAME_MAP.get(method), tag )) spec = _UNIVERSAL_SPECS[tag] value = spec(contents=contents, class_=class_) ber_indef = method == 1 and value.method == 0 and trailer == b'\x00\x00' if ber_indef and isinstance(value, Constructable): value._indefinite = True value.method = method if not header_set: value._header = header value._trailer = trailer or b'' # Destroy any default value that our contents have overwritten value._native = None if nested_spec: try: value.parse(nested_spec) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(value),) + args raise e return value def _parse_build(encoded_data, pointer=0, spec=None, spec_params=None, strict=False): """ Parses a byte string generically, or using a spec with optional params :param encoded_data: A byte string that contains BER-encoded data :param pointer: The index in the byte string to parse from :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A 2-element tuple: - 0: An object of the type spec, or if not specified, a child of Asn1Value - 1: An integer indicating how many bytes were consumed """ encoded_len = len(encoded_data) info, new_pointer = _parse(encoded_data, encoded_len, pointer) if strict and new_pointer != pointer + encoded_len: extra_bytes = pointer + encoded_len - new_pointer raise ValueError('Extra data - %d bytes of trailing data were provided' % extra_bytes) return (_build(*info, spec=spec, spec_params=spec_params), new_pointer)
mit
0daf4d2e708425b0135406da15a07a70
29.075581
119
0.516985
4.60977
false
false
false
false
wbond/asn1crypto
dev/_import.py
2
3489
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import imp import sys import os from . import build_root, package_name, package_root if sys.version_info < (3,): getcwd = os.getcwdu else: getcwd = os.getcwd def _import_from(mod, path, mod_dir=None, allow_error=False): """ Imports a module from a specific path :param mod: A unicode string of the module name :param path: A unicode string to the directory containing the module :param mod_dir: If the sub directory of "path" is different than the "mod" name, pass the sub directory as a unicode string :param allow_error: If an ImportError should be raised when the module can't be imported :return: None if not loaded, otherwise the module """ if mod_dir is None: mod_dir = mod.replace('.', os.sep) if not os.path.exists(path): return None if not os.path.exists(os.path.join(path, mod_dir)) \ and not os.path.exists(os.path.join(path, mod_dir + '.py')): return None if os.sep in mod_dir: append, mod_dir = mod_dir.rsplit(os.sep, 1) path = os.path.join(path, append) try: mod_info = imp.find_module(mod_dir, [path]) return imp.load_module(mod, *mod_info) except ImportError: if allow_error: raise return None def _preload(require_oscrypto, print_info): """ Preloads asn1crypto and optionally oscrypto from a local source checkout, or from a normal install :param require_oscrypto: A bool if oscrypto needs to be preloaded :param print_info: A bool if info about asn1crypto and oscrypto should be printed """ if print_info: print('Working dir: ' + getcwd()) print('Python ' + sys.version.replace('\n', '')) asn1crypto = None oscrypto = None if require_oscrypto: # Some CI services don't use the package name for the dir if package_name == 'oscrypto': oscrypto_dir = package_root else: oscrypto_dir = os.path.join(build_root, 'oscrypto') oscrypto_tests = None if os.path.exists(oscrypto_dir): oscrypto_tests = _import_from('oscrypto_tests', oscrypto_dir, 'tests') if oscrypto_tests is None: import oscrypto_tests asn1crypto, oscrypto = oscrypto_tests.local_oscrypto() else: if package_name == 'asn1crypto': asn1crypto_dir = package_root else: asn1crypto_dir = os.path.join(build_root, 'asn1crypto') if os.path.exists(asn1crypto_dir): asn1crypto = _import_from('asn1crypto', asn1crypto_dir) if asn1crypto is None: import asn1crypto if print_info: print( '\nasn1crypto: %s, %s' % ( asn1crypto.__version__, os.path.dirname(asn1crypto.__file__) ) ) if require_oscrypto: backend = oscrypto.backend() if backend == 'openssl': from oscrypto._openssl._libcrypto import libcrypto_version backend = '%s (%s)' % (backend, libcrypto_version) print( 'oscrypto: %s, %s backend, %s' % ( oscrypto.__version__, backend, os.path.dirname(oscrypto.__file__) ) )
mit
a1193a484631bb22b9e30df10f0cc1ef
27.834711
82
0.579536
3.876667
false
true
false
false
nschloe/meshio
src/meshio/neuroglancer/_neuroglancer.py
1
2824
""" Neuroglancer format, used in large-scale neuropil segmentation data. Adapted from https://github.com/HumanBrainProject/neuroglancer-scripts/blob/1fcabb613a715ba17c65d52596dec3d687ca3318/src/neuroglancer_scripts/mesh.py (MIT license) """ import struct import numpy as np from .._common import warn from .._exceptions import ReadError from .._files import open_file from .._helpers import register_format from .._mesh import CellBlock, Mesh def write(filename, mesh): with open_file(filename, "wb") as f: write_buffer(f, mesh) def write_buffer(f, mesh): """Store a mesh in Neuroglancer pre-computed format. :param file: a file-like object opened in binary mode (its ``write`` method will be called with :class:`bytes` objects). :param meshio.Mesh mesh: Mesh object to write """ vertices = np.asarray(mesh.points, "<f") skip = [c for c in mesh.cells if c.type != "triangle"] if skip: warn('Neuroglancer only supports triangle cells. Skipping {", ".join(skip)}.') f.write(struct.pack("<I", vertices.shape[0])) f.write(vertices.tobytes(order="C")) for c in filter(lambda c: c.type == "triangle", mesh.cells): f.write(np.asarray(c.data, "<I").tobytes(order="C")) def read(filename): with open_file(filename, "rb") as f: return read_buffer(f) def read_buffer(file): """Load a mesh in Neuroglancer pre-computed format. :param file: a file-like object opened in binary mode (its ``read`` method is expected to return :class:`bytes` objects). :returns meshio.Mesh: """ num_vertices = struct.unpack("<I", file.read(4))[0] # TODO handle format errors # # Use frombuffer instead of np.fromfile, because the latter expects a # real file and performs direct I/O on file.fileno(), which can fail or # read garbage e.g. if the file is an instance of gzip.GzipFile. buf = file.read(4 * 3 * num_vertices) if len(buf) != 4 * 3 * num_vertices: raise ReadError("The precomputed mesh data is too short") flat_vertices = np.frombuffer(buf, "<f") vertices = np.reshape(flat_vertices, (num_vertices, 3),).copy( order="C" ) # TODO remove copy # BUG: this could easily exhaust memory if reading a large file that is not # in precomputed format. buf = file.read() if len(buf) % (3 * 4) != 0: raise ReadError("The size of the precomputed mesh data is not adequate") flat_triangles = np.frombuffer(buf, "<I") triangles = np.reshape(flat_triangles, (-1, 3)).copy(order="C") # TODO remove copy if np.any(triangles > num_vertices): raise ReadError("The mesh references nonexistent vertices") return Mesh(vertices, [CellBlock("triangle", triangles)]) register_format("neuroglancer", [], read, {"neuroglancer": write})
mit
e9563fba9266bdd41e7ac9db13a90be6
36.157895
163
0.670326
3.410628
false
false
false
false
nschloe/meshio
tests/legacy_writer.py
1
6820
import logging import numpy as np # https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html vtk_to_meshio_type = { 0: "empty", 1: "vertex", # 2: 'poly_vertex', 3: "line", # 4: 'poly_line', 5: "triangle", # 6: 'triangle_strip', 7: "polygon", # 8: 'pixel', 9: "quad", 10: "tetra", # 11: 'voxel', 12: "hexahedron", 13: "wedge", 14: "pyramid", 15: "penta_prism", 16: "hexa_prism", 21: "line3", 22: "triangle6", 23: "quad8", 24: "tetra10", 25: "hexahedron20", 26: "wedge15", 27: "pyramid13", 28: "quad9", 29: "hexahedron27", 30: "quad6", 31: "wedge12", 32: "wedge18", 33: "hexahedron24", 34: "triangle7", 35: "line4", # # 60: VTK_HIGHER_ORDER_EDGE, # 61: VTK_HIGHER_ORDER_TRIANGLE, # 62: VTK_HIGHER_ORDER_QUAD, # 63: VTK_HIGHER_ORDER_POLYGON, # 64: VTK_HIGHER_ORDER_TETRAHEDRON, # 65: VTK_HIGHER_ORDER_WEDGE, # 66: VTK_HIGHER_ORDER_PYRAMID, # 67: VTK_HIGHER_ORDER_HEXAHEDRON, } def _get_writer(filetype, filename): import vtk if filetype in "vtk-ascii": logging.warning("VTK ASCII files are only meant for debugging.") writer = vtk.vtkUnstructuredGridWriter() writer.SetFileTypeToASCII() elif filetype == "vtk-binary": writer = vtk.vtkUnstructuredGridWriter() writer.SetFileTypeToBinary() elif filetype == "vtu-ascii": logging.warning("VTU ASCII files are only meant for debugging.") writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToAscii() elif filetype == "vtu-binary": writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToBinary() elif filetype == "xdmf2": writer = vtk.vtkXdmfWriter() elif filetype == "xdmf3": writer = vtk.vtkXdmf3Writer() else: assert filetype == "exodus", f"Unknown file type '{filename}'." writer = vtk.vtkExodusIIWriter() # if the mesh contains vtkmodeldata information, make use of it # and write out all time steps. writer.WriteAllTimeStepsOn() return writer def write(filetype, filename, mesh): import vtk def _create_vtkarray(X, name): array = vtk.util.numpy_support.numpy_to_vtk(X, deep=1) array.SetName(name) return array # assert data integrity for val in mesh.point_data.values(): assert len(val) == len(mesh.points), "Point data mismatch." for key, value in mesh.cell_data.items(): assert key in mesh.cells, "Cell data without cell" for key2 in value: assert len(value[key2]) == len(mesh.cells[key]), "Cell data mismatch." vtk_mesh = _generate_vtk_mesh(mesh.points, mesh.cells) # add point data pd = vtk_mesh.GetPointData() for name, X in mesh.point_data.items(): # There is a naming inconsistency in VTK when it comes to multivectors # in Exodus files: # If a vector 'v' has two components, they are called 'v_x', 'v_y' # (note the underscore), if it has three, then they are called 'vx', # 'vy', 'vz'. See bug <https://vtk.org/Bug/view.php?id=15894>. # For VT{K,U} files, no underscore is ever added. pd.AddArray(_create_vtkarray(X, name)) # Add cell data. # The cell_data is structured like # # cell_type -> # key -> array # key -> array # [...] # cell_type -> # key -> array # key -> array # [...] # [...] # # VTK expects one array for each `key`, so assemble the keys across all # mesh_types. This requires each key to be present for each mesh_type, of # course. all_keys = [] for cell_type in mesh.cell_data: all_keys += mesh.cell_data[cell_type].keys() # create unified cell data for key in all_keys: for cell_type in mesh.cell_data: assert key in mesh.cell_data[cell_type] unified_cell_data = { key: np.concatenate([value[key] for value in mesh.cell_data.values()]) for key in all_keys } # add the array data to the mesh cd = vtk_mesh.GetCellData() for name, array in unified_cell_data.items(): cd.AddArray(_create_vtkarray(array, name)) # add field data fd = vtk_mesh.GetFieldData() for key, value in mesh.field_data.items(): fd.AddArray(_create_vtkarray(value, key)) writer = _get_writer(filetype, filename) writer.SetFileName(filename) try: writer.SetInput(vtk_mesh) except AttributeError: writer.SetInputData(vtk_mesh) writer.Write() return def _generate_vtk_mesh(points, cells): import vtk from vtk.util import numpy as numpy_support mesh = vtk.vtkUnstructuredGrid() # set points vtk_points = vtk.vtkPoints() # Not using a deep copy here results in a segfault. vtk_array = numpy_support.numpy_to_vtk(points, deep=True) vtk_points.SetData(vtk_array) mesh.SetPoints(vtk_points) # Set cells. meshio_to_vtk_type = {y: x for x, y in vtk_to_meshio_type.items()} # create cell_array. It's a one-dimensional vector with # (num_points2, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ... cell_types = [] cell_offsets = [] cell_connectivity = [] len_array = 0 for meshio_type, data in cells.items(): numcells, num_local_nodes = data.shape vtk_type = meshio_to_vtk_type[meshio_type] # add cell types cell_types.append(np.empty(numcells, dtype=np.ubyte)) cell_types[-1].fill(vtk_type) # add cell offsets cell_offsets.append( np.arange( len_array, len_array + numcells * (num_local_nodes + 1), num_local_nodes + 1, dtype=np.int64, ) ) cell_connectivity.append( np.c_[num_local_nodes * np.ones(numcells, dtype=data.dtype), data].flatten() ) len_array += len(cell_connectivity[-1]) cell_types = np.concatenate(cell_types) cell_offsets = np.concatenate(cell_offsets) cell_connectivity = np.concatenate(cell_connectivity) connectivity = vtk.util.numpy_support.numpy_to_vtkIdTypeArray( cell_connectivity.astype(np.int64), deep=1 ) # wrap the data into a vtkCellArray cell_array = vtk.vtkCellArray() cell_array.SetCells(len(cell_types), connectivity) # Add cell data to the mesh mesh.SetCells( numpy_support.numpy_to_vtk( cell_types, deep=1, array_type=vtk.vtkUnsignedCharArray().GetDataType() ), numpy_support.numpy_to_vtk( cell_offsets, deep=1, array_type=vtk.vtkIdTypeArray().GetDataType() ), cell_array, ) return mesh
mit
22d89300df1022725546dd1407df31b1
29.176991
88
0.600147
3.354648
false
false
false
false
graphql-python/graphene
graphene/relay/tests/test_node.py
1
5609
import re from textwrap import dedent from graphql_relay import to_global_id from ...types import ObjectType, Schema, String from ..node import Node, is_node class SharedNodeFields: shared = String() something_else = String() def resolve_something_else(*_): return "----" class MyNode(ObjectType): class Meta: interfaces = (Node,) name = String() @staticmethod def get_node(info, id): return MyNode(name=str(id)) class MyOtherNode(SharedNodeFields, ObjectType): extra_field = String() class Meta: interfaces = (Node,) def resolve_extra_field(self, *_): return "extra field info." @staticmethod def get_node(info, id): return MyOtherNode(shared=str(id)) class RootQuery(ObjectType): first = String() node = Node.Field() only_node = Node.Field(MyNode) only_node_lazy = Node.Field(lambda: MyNode) schema = Schema(query=RootQuery, types=[MyNode, MyOtherNode]) def test_node_good(): assert "id" in MyNode._meta.fields assert is_node(MyNode) assert not is_node(object) assert not is_node("node") def test_node_query(): executed = schema.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"node": {"name": "1"}} def test_subclassed_node_query(): executed = schema.execute( '{ node(id:"%s") { ... on MyOtherNode { shared, extraField, somethingElse } } }' % to_global_id("MyOtherNode", 1) ) assert not executed.errors assert executed.data == { "node": { "shared": "1", "extraField": "extra field info.", "somethingElse": "----", } } def test_node_requesting_non_node(): executed = schema.execute( '{ node(id:"%s") { __typename } } ' % Node.to_global_id("RootQuery", 1) ) assert executed.errors assert re.match( r"ObjectType .* does not implement the .* interface.", executed.errors[0].message, ) assert executed.data == {"node": None} def test_node_requesting_unknown_type(): executed = schema.execute( '{ node(id:"%s") { __typename } } ' % Node.to_global_id("UnknownType", 1) ) assert executed.errors assert re.match(r"Relay Node .* not found in schema", executed.errors[0].message) assert executed.data == {"node": None} def test_node_query_incorrect_id(): executed = schema.execute( '{ node(id:"%s") { ... on MyNode { name } } }' % "something:2" ) assert executed.errors assert re.match(r"Unable to parse global ID .*", executed.errors[0].message) assert executed.data == {"node": None} def test_node_field(): node_field = Node.Field() assert node_field.type == Node assert node_field.node_type == Node def test_node_field_custom(): node_field = Node.Field(MyNode) assert node_field.type == MyNode assert node_field.node_type == Node def test_node_field_args(): field_args = { "name": "my_custom_name", "description": "my_custom_description", "deprecation_reason": "my_custom_deprecation_reason", } node_field = Node.Field(**field_args) for field_arg, value in field_args.items(): assert getattr(node_field, field_arg) == value def test_node_field_only_type(): executed = schema.execute( '{ onlyNode(id:"%s") { __typename, name } } ' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"onlyNode": {"__typename": "MyNode", "name": "1"}} def test_node_field_only_type_wrong(): executed = schema.execute( '{ onlyNode(id:"%s") { __typename, name } } ' % Node.to_global_id("MyOtherNode", 1) ) assert len(executed.errors) == 1 assert str(executed.errors[0]).startswith("Must receive a MyNode id.") assert executed.data == {"onlyNode": None} def test_node_field_only_lazy_type(): executed = schema.execute( '{ onlyNodeLazy(id:"%s") { __typename, name } } ' % Node.to_global_id("MyNode", 1) ) assert not executed.errors assert executed.data == {"onlyNodeLazy": {"__typename": "MyNode", "name": "1"}} def test_node_field_only_lazy_type_wrong(): executed = schema.execute( '{ onlyNodeLazy(id:"%s") { __typename, name } } ' % Node.to_global_id("MyOtherNode", 1) ) assert len(executed.errors) == 1 assert str(executed.errors[0]).startswith("Must receive a MyNode id.") assert executed.data == {"onlyNodeLazy": None} def test_str_schema(): assert ( str(schema).strip() == dedent( ''' schema { query: RootQuery } type MyNode implements Node { """The ID of the object""" id: ID! name: String } """An object with an ID""" interface Node { """The ID of the object""" id: ID! } type MyOtherNode implements Node { """The ID of the object""" id: ID! shared: String somethingElse: String extraField: String } type RootQuery { first: String node( """The ID of the object""" id: ID! ): Node onlyNode( """The ID of the object""" id: ID! ): MyNode onlyNodeLazy( """The ID of the object""" id: ID! ): MyNode } ''' ).strip() )
mit
8d08634deb58d54566764e2d9048adf2
24.495455
88
0.570333
3.651693
false
true
false
false
nschloe/meshio
tests/test_flac3d.py
1
1540
import pathlib import numpy as np import pytest import meshio from . import helpers @pytest.mark.parametrize( "mesh", [ helpers.empty_mesh, helpers.tet_mesh, helpers.hex_mesh, helpers.tet_mesh, helpers.add_cell_sets(helpers.tet_mesh), ], ) @pytest.mark.parametrize("binary", [False, True]) def test(mesh, binary, tmp_path): # mesh.write("out.f3grid") helpers.write_read( tmp_path, lambda f, m: meshio.flac3d.write(f, m, binary=binary), meshio.flac3d.read, mesh, 1.0e-15, ) @pytest.mark.parametrize( "filename", ["flac3d_mesh_ex.f3grid", "flac3d_mesh_ex_bin.f3grid"], ) def test_reference_file(filename): this_dir = pathlib.Path(__file__).resolve().parent filename = this_dir / "meshes" / "flac3d" / filename mesh = meshio.read(filename) # points assert np.isclose(mesh.points.sum(), 307.0) # cells ref_num_cells = [ ("quad", 15), ("triangle", 3), ("hexahedron", 45), ("pyramid", 9), ("hexahedron", 18), ("wedge", 9), ("hexahedron", 6), ("wedge", 3), ("hexahedron", 6), ("wedge", 3), ("pyramid", 6), ("tetra", 3), ] assert [ (cell_block.type, len(cell_block)) for cell_block in mesh.cells ] == ref_num_cells # Cell sets for arr in mesh.cell_sets.values(): assert len(arr) == 12 assert [len(arr) for arr in mesh.cell_sets.values()] == [12, 12, 12, 12, 12]
mit
f16750adcbe0aa9a3cf4bc3a82c5ce35
21.985075
80
0.553896
3.123732
false
true
false
false
graphql-python/graphene
graphene/relay/tests/test_global_id.py
1
1566
from graphql_relay import to_global_id from ...types import ID, NonNull, ObjectType, String from ...types.definitions import GrapheneObjectType from ..node import GlobalID, Node class CustomNode(Node): class Meta: name = "Node" class User(ObjectType): class Meta: interfaces = [CustomNode] name = String() class Info: def __init__(self, parent_type): self.parent_type = GrapheneObjectType( graphene_type=parent_type, name=parent_type._meta.name, description=parent_type._meta.description, fields=None, is_type_of=parent_type.is_type_of, interfaces=None, ) def test_global_id_defaults_to_required_and_node(): gid = GlobalID() assert isinstance(gid.type, NonNull) assert gid.type.of_type == ID assert gid.node == Node def test_global_id_allows_overriding_of_node_and_required(): gid = GlobalID(node=CustomNode, required=False) assert gid.type == ID assert gid.node == CustomNode def test_global_id_defaults_to_info_parent_type(): my_id = "1" gid = GlobalID() id_resolver = gid.wrap_resolve(lambda *_: my_id) my_global_id = id_resolver(None, Info(User)) assert my_global_id == to_global_id(User._meta.name, my_id) def test_global_id_allows_setting_customer_parent_type(): my_id = "1" gid = GlobalID(parent_type=User) id_resolver = gid.wrap_resolve(lambda *_: my_id) my_global_id = id_resolver(None, None) assert my_global_id == to_global_id(User._meta.name, my_id)
mit
6135e90853c296419a57f7f1310c3487
26
63
0.64751
3.317797
false
true
false
false
desec-io/desec-stack
api/desecapi/views/dyndns.py
1
5265
import base64 import binascii from functools import cached_property from rest_framework import generics from rest_framework.authentication import get_authorization_header from rest_framework.exceptions import NotFound, ValidationError from rest_framework.response import Response from desecapi import metrics from desecapi.authentication import ( BasicTokenAuthentication, TokenAuthentication, URLParamAuthentication, ) from desecapi.exceptions import ConcurrencyException from desecapi.models import Domain from desecapi.pdns_change_tracker import PDNSChangeTracker from desecapi.permissions import TokenHasDomainDynDNSPermission from desecapi.renderers import PlainTextRenderer from desecapi.serializers import RRsetSerializer class DynDNS12UpdateView(generics.GenericAPIView): authentication_classes = ( TokenAuthentication, BasicTokenAuthentication, URLParamAuthentication, ) permission_classes = (TokenHasDomainDynDNSPermission,) renderer_classes = [PlainTextRenderer] serializer_class = RRsetSerializer throttle_scope = "dyndns" @property def throttle_scope_bucket(self): return self.domain.name def _find_ip(self, params, separator): # Check URL parameters for p in params: try: param = self.request.query_params[p] except KeyError: continue if separator in param or param in ("", "preserve"): return param # Check remote IP address client_ip = self.request.META.get("REMOTE_ADDR") if separator in client_ip: return client_ip # give up return None @cached_property def qname(self): # hostname parameter try: if self.request.query_params["hostname"] != "YES": return self.request.query_params["hostname"].lower() except KeyError: pass # host_id parameter try: return self.request.query_params["host_id"].lower() except KeyError: pass # http basic auth username try: domain_name = ( base64.b64decode( get_authorization_header(self.request) .decode() .split(" ")[1] .encode() ) .decode() .split(":")[0] ) if domain_name and "@" not in domain_name: return domain_name.lower() except (binascii.Error, IndexError, UnicodeDecodeError): pass # username parameter try: return self.request.query_params["username"].lower() except KeyError: pass # only domain associated with this user account try: return self.request.user.domains.get().name except Domain.MultipleObjectsReturned: raise ValidationError( detail={ "detail": "Request does not properly specify domain for update.", "code": "domain-unspecified", } ) except Domain.DoesNotExist: metrics.get("desecapi_dynDNS12_domain_not_found").inc() raise NotFound("nohost") @cached_property def domain(self): try: return Domain.objects.filter_qname( self.qname, owner=self.request.user ).order_by("-name_length")[0] except (IndexError, ValueError): raise NotFound("nohost") @property def subname(self): return self.qname.rpartition(f".{self.domain.name}")[0] def get_serializer_context(self): return { **super().get_serializer_context(), "domain": self.domain, "minimum_ttl": 60, } def get_queryset(self): return self.domain.rrset_set.filter( subname=self.subname, type__in=["A", "AAAA"] ) def get(self, request, *args, **kwargs): instances = self.get_queryset().all() record_params = { "A": self._find_ip(["myip", "myipv4", "ip"], separator="."), "AAAA": self._find_ip(["myipv6", "ipv6", "myip", "ip"], separator=":"), } data = [ { "type": type_, "subname": self.subname, "ttl": 60, "records": [ip_param] if ip_param else [], } for type_, ip_param in record_params.items() if ip_param != "preserve" ] serializer = self.get_serializer(instances, data=data, many=True, partial=True) try: serializer.is_valid(raise_exception=True) except ValidationError as e: if any( any( getattr(non_field_error, "code", "") == "unique" for non_field_error in err.get("non_field_errors", []) ) for err in e.detail ): raise ConcurrencyException from e raise e with PDNSChangeTracker(): serializer.save() return Response("good", content_type="text/plain")
mit
2482569d74b9dd82f26755c845f25c7c
29.970588
87
0.565052
4.586237
false
false
false
false
desec-io/desec-stack
api/desecapi/management/commands/sync-from-pdns.py
1
1966
from django.core.management import BaseCommand, CommandError from django.db import transaction from desecapi import pdns from desecapi.models import Domain, RRset, RR, RR_SET_TYPES_AUTOMATIC class Command(BaseCommand): help = "Import authoritative data from pdns, making the local database consistent with pdns." def add_arguments(self, parser): parser.add_argument( "domain-name", nargs="*", help="Domain name to import. If omitted, will import all domains that are known locally.", ) def handle(self, *args, **options): domains = Domain.objects.all() if options["domain-name"]: domains = domains.filter(name__in=options["domain-name"]) domain_names = domains.values_list("name", flat=True) for domain_name in options["domain-name"]: if domain_name not in domain_names: raise CommandError("{} is not a known domain".format(domain_name)) for domain in domains: self.stdout.write("%s ..." % domain.name, ending="") try: self._sync_domain(domain) self.stdout.write(" synced") except Exception as e: self.stdout.write(" failed") msg = "Error while processing {}: {}".format(domain.name, e) raise CommandError(msg) @staticmethod @transaction.atomic def _sync_domain(domain): domain.rrset_set.all().delete() rrsets = [] rrs = [] for rrset_data in pdns.get_rrset_datas(domain): if rrset_data["type"] in RR_SET_TYPES_AUTOMATIC: continue records = rrset_data.pop("records") rrset = RRset(**rrset_data) rrsets.append(rrset) rrs.extend([RR(rrset=rrset, content=record) for record in records]) RRset.objects.bulk_create(rrsets) RR.objects.bulk_create(rrs)
mit
e22efd10763e830b22e59e69aacdf490
36.09434
102
0.591048
4.130252
false
false
false
false
desec-io/desec-stack
api/desecapi/models/captcha.py
1
1702
from __future__ import annotations import secrets import string import uuid from django.conf import settings from django.db import models from django.utils import timezone from django_prometheus.models import ExportModelOperationsMixin from desecapi import metrics def captcha_default_content(kind: str) -> str: if kind == Captcha.Kind.IMAGE: alphabet = (string.ascii_uppercase + string.digits).translate( {ord(c): None for c in "IO0"} ) length = 5 elif kind == Captcha.Kind.AUDIO: alphabet = string.digits length = 8 else: raise ValueError(f"Unknown Captcha kind: {kind}") content = "".join([secrets.choice(alphabet) for _ in range(length)]) metrics.get("desecapi_captcha_content_created").labels(kind).inc() return content class Captcha(ExportModelOperationsMixin("Captcha"), models.Model): class Kind(models.TextChoices): IMAGE = "image" AUDIO = "audio" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) content = models.CharField(max_length=24, default="") kind = models.CharField(choices=Kind.choices, default=Kind.IMAGE, max_length=24) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.content: self.content = captcha_default_content(self.kind) def verify(self, solution: str): age = timezone.now() - self.created self.delete() return ( str(solution).upper().strip() == self.content # solution correct and age <= settings.CAPTCHA_VALIDITY_PERIOD # not expired )
mit
e4abdc389f2f3fcfb3d78239a2ee0c3d
31.113208
84
0.658049
3.876993
false
false
false
false
desec-io/desec-stack
api/desecapi/management/commands/sync-to-pdns.py
1
2885
from django.core.management import BaseCommand, CommandError, call_command from django.db import transaction from desecapi import pdns from desecapi.exceptions import PDNSException from desecapi.models import Domain from desecapi.pdns_change_tracker import PDNSChangeTracker class Command(BaseCommand): help = "Sync RRsets from local API database to pdns." def add_arguments(self, parser): parser.add_argument( "domain-name", nargs="*", help="Domain name to sync. If omitted, will import all API domains.", ) def handle(self, *args, **options): domains = Domain.objects.all() if options["domain-name"]: domains = domains.filter(name__in=options["domain-name"]) domain_names = domains.values_list("name", flat=True) for domain_name in options["domain-name"]: if domain_name not in domain_names: raise CommandError("{} is not a known domain".format(domain_name)) catalog_alignment = False for domain in domains: self.stdout.write("%s ..." % domain.name, ending="") try: created = self._sync_domain(domain) if created: self.stdout.write(f" created (was missing) ...", ending="") catalog_alignment = True self.stdout.write(" synced") except Exception as e: self.stdout.write(" failed") msg = "Error while processing {}: {}".format(domain.name, e) raise CommandError(msg) if catalog_alignment: call_command("align-catalog-zone") @staticmethod @transaction.atomic def _sync_domain(domain): created = False # Create domain on pdns if it does not exist try: PDNSChangeTracker.CreateDomain(domain_name=domain.name).pdns_do() except PDNSException as e: # Domain already exists if e.response.status_code == 409: pass else: raise e else: created = True # modifications actually merged with additions in CreateUpdateDeleteRRSets modifications = { (rrset.type, rrset.subname) for rrset in domain.rrset_set.all() } deletions = { (rrset["type"], rrset["subname"]) for rrset in pdns.get_rrset_datas(domain) } - modifications deletions.discard(("SOA", "")) # do not remove SOA record # Update zone on nslord, propagate to nsmaster PDNSChangeTracker.CreateUpdateDeleteRRSets( domain.name, set(), modifications, deletions ).pdns_do() pdns._pdns_put( pdns.NSMASTER, "/zones/{}/axfr-retrieve".format(pdns.pdns_id(domain.name)) ) return created
mit
4fd667e4d17517c979dee603aba6d4c2
34.182927
87
0.585442
4.384498
false
false
false
false
desec-io/desec-stack
api/desecapi/views/records.py
1
5044
from django.http import Http404 from rest_framework import generics from rest_framework.exceptions import PermissionDenied from rest_framework.permissions import IsAuthenticated, SAFE_METHODS from desecapi import models, permissions from desecapi.pdns_change_tracker import PDNSChangeTracker from desecapi.serializers import RRsetSerializer from .base import IdempotentDestroyMixin class EmptyPayloadMixin: def initialize_request(self, request, *args, **kwargs): # noinspection PyUnresolvedReferences request = super().initialize_request(request, *args, **kwargs) if request.stream is None: # In this case, data and files are both empty, so we can set request.data=None (instead of the default {}). # This allows distinguishing missing payload from empty dict payload. # See https://github.com/encode/django-rest-framework/pull/7195 request._full_data = None return request class DomainViewMixin: @property def domain(self): try: # noinspection PyUnresolvedReferences return self.request.user.domains.get(name=self.kwargs["name"]) except models.Domain.DoesNotExist: raise Http404 class RRsetView(DomainViewMixin): serializer_class = RRsetSerializer permission_classes = ( IsAuthenticated, permissions.IsAPIToken | permissions.MFARequiredIfEnabled, permissions.IsDomainOwner, permissions.TokenHasDomainRRsetsPermission, ) @property def throttle_scope(self): # noinspection PyUnresolvedReferences return ( "dns_api_cheap" if self.request.method in SAFE_METHODS else "dns_api_per_domain_expensive" ) @property def throttle_scope_bucket(self): # Note: bucket should remain constant even when domain is recreated # noinspection PyUnresolvedReferences return None if self.request.method in SAFE_METHODS else self.kwargs["name"] def get_queryset(self): return self.domain.rrset_set def get_serializer_context(self): # noinspection PyUnresolvedReferences return {**super().get_serializer_context(), "domain": self.domain} def perform_update(self, serializer): with PDNSChangeTracker(): # noinspection PyUnresolvedReferences super().perform_update(serializer) class RRsetDetail( RRsetView, IdempotentDestroyMixin, generics.RetrieveUpdateDestroyAPIView ): def get_object(self): queryset = self.filter_queryset(self.get_queryset()) filter_kwargs = {k: self.kwargs[k] for k in ["subname", "type"]} obj = generics.get_object_or_404(queryset, **filter_kwargs) # May raise a permission denied self.check_object_permissions(self.request, obj) return obj def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) if response.data is None: response.status_code = 204 return response def perform_destroy(self, instance): with PDNSChangeTracker(): super().perform_destroy(instance) class RRsetList( RRsetView, EmptyPayloadMixin, generics.ListCreateAPIView, generics.UpdateAPIView ): def get_queryset(self): rrsets = super().get_queryset() for filter_field in ("subname", "type"): value = self.request.query_params.get(filter_field) if value is not None: # TODO consider moving this if ( filter_field == "type" and value in models.records.RR_SET_TYPES_AUTOMATIC ): raise PermissionDenied( "You cannot tinker with the %s RRset." % value ) rrsets = rrsets.filter(**{"%s__exact" % filter_field: value}) return ( rrsets.all() ) # without .all(), cache is sometimes inconsistent with actual state in bulk tests. (Why?) def get_object(self): # For this view, the object we're operating on is the queryset that one can also GET. Serializing a queryset # is fine as per https://www.django-rest-framework.org/api-guide/serializers/#serializing-multiple-objects. # We skip checking object permissions here to avoid evaluating the queryset. The user can access all his RRsets # anyways. return self.filter_queryset(self.get_queryset()) def get_serializer(self, *args, **kwargs): kwargs = kwargs.copy() if "many" not in kwargs: if self.request.method in ["POST"]: kwargs["many"] = isinstance(kwargs.get("data"), list) elif self.request.method in ["PATCH", "PUT"]: kwargs["many"] = True return super().get_serializer(*args, **kwargs) def perform_create(self, serializer): with PDNSChangeTracker(): super().perform_create(serializer)
mit
9a5843f983a719f999b3c348e8fb8e74
33.786207
119
0.64433
4.382276
false
false
false
false
desec-io/desec-stack
test/e2e2/spec/test_api_user_mgmt.py
1
1936
from conftest import DeSECAPIV1Client def test_register(api_anon: DeSECAPIV1Client): email = "e2e2@desec.test" password = "foobar12" assert api_anon.register(email, password)[1].json() == {"detail": "Welcome!"} assert "token" in api_anon.login(email, password).json() api = api_anon assert api.get("/").json() == { "domains": f"{api.base_url}/domains/", "tokens": f"{api.base_url}/auth/tokens/", "logout": f"{api.base_url}/auth/logout/", "account": { "change-email": f"{api.base_url}/auth/account/change-email/", "delete": f"{api.base_url}/auth/account/delete/", "reset-password": f"{api.base_url}/auth/account/reset-password/", "show": f"{api.base_url}/auth/account/", }, } def test_register2(api_user: DeSECAPIV1Client): user = api_user.get("/auth/account/").json() # Verify that email address local part is stored as provided, and hostname is lowercased email_name, domain_part = api_user.email.strip().rsplit('@', 1) assert user["email"] == email_name + '@' + domain_part.lower() assert api_user.headers['Authorization'].startswith('Token ') assert len(api_user.headers['Authorization']) > len('Token ') + 10 def test_register_login_email_case_variation(api_user: DeSECAPIV1Client, api_anon: DeSECAPIV1Client): # Invert email casing email2 = ''.join(l.lower() if l.isupper() else l.upper() for l in api_user.email) password2 = "foobar13" # Try registering an account (should always return success, even if address with any casing is taken) assert api_anon.register(email2, password2)[1].json() == {"detail": "Welcome!"} # Verify that login is possible regardless of email spelling, but only with the first user's password assert api_anon.login(email2, password2).status_code == 403 assert "token" in api_anon.login(email2, api_user.password).json()
mit
52602ca0178d34d37671924acc0dece8
42.022222
105
0.653409
3.432624
false
true
false
false
desec-io/desec-stack
api/desecapi/tests/test_token_domain_policy.py
1
19694
from contextlib import nullcontext from django.db import transaction from django.db.utils import IntegrityError from rest_framework import status from rest_framework.test import APIClient from desecapi import models from desecapi.tests.base import DomainOwnerTestCase class TokenDomainPolicyClient(APIClient): def _request(self, method, url, *, using, **kwargs): if using is not None: kwargs.update(HTTP_AUTHORIZATION=f"Token {using.plain}") return method(url, **kwargs) def _request_policy(self, method, target, *, using, domain, **kwargs): domain = domain or "default" url = DomainOwnerTestCase.reverse( "v1:token_domain_policies-detail", token_id=target.id, domain__name=domain ) return self._request(method, url, using=using, **kwargs) def _request_policies(self, method, target, *, using, **kwargs): url = DomainOwnerTestCase.reverse( "v1:token_domain_policies-list", token_id=target.id ) return self._request(method, url, using=using, **kwargs) def list_policies(self, target, *, using): return self._request_policies(self.get, target, using=using) def create_policy(self, target, *, using, **kwargs): return self._request_policies(self.post, target, using=using, **kwargs) def get_policy(self, target, *, using, domain): return self._request_policy(self.get, target, using=using, domain=domain) def patch_policy(self, target, *, using, domain, **kwargs): return self._request_policy( self.patch, target, using=using, domain=domain, **kwargs ) def delete_policy(self, target, *, using, domain): return self._request_policy(self.delete, target, using=using, domain=domain) class TokenDomainPolicyTestCase(DomainOwnerTestCase): client_class = TokenDomainPolicyClient default_data = dict(perm_dyndns=False, perm_rrsets=False) def setUp(self): super().setUp() self.client.credentials() # remove default credential (corresponding to domain owner) self.token_manage = self.create_token(self.owner, perm_manage_tokens=True) self.other_token = self.create_token(self.user) def test_policy_lifecycle_without_management_permission(self): # Prepare (with management token) data = dict(domain=None, perm_rrsets=True) response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_201_CREATED) response = self.client.create_policy( self.token_manage, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_201_CREATED) # Self-inspection is fine ## List response = self.client.list_policies(self.token, using=self.token) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) ## Get response = self.client.get_policy(self.token, using=self.token, domain=None) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, self.default_data | data) # Inspection of other tokens forbidden ## List response = self.client.list_policies(self.token_manage, using=self.token) self.assertStatus(response, status.HTTP_403_FORBIDDEN) ## Get response = self.client.get_policy( self.token_manage, using=self.token, domain=None ) self.assertStatus(response, status.HTTP_403_FORBIDDEN) # Write operations forbidden (self and other) for target in [self.token, self.token_manage]: # Create response = self.client.create_policy(target, using=self.token) self.assertStatus(response, status.HTTP_403_FORBIDDEN) # Change data = dict( domain=self.my_domains[1].name, perm_dyndns=False, perm_rrsets=True ) response = self.client.patch_policy( target, using=self.token, domain=self.my_domains[0].name, data=data ) self.assertStatus(response, status.HTTP_403_FORBIDDEN) # Delete response = self.client.delete_policy(target, using=self.token, domain=None) self.assertStatus(response, status.HTTP_403_FORBIDDEN) def test_policy_lifecycle(self): # Can't do anything unauthorized response = self.client.list_policies(self.token, using=None) self.assertStatus(response, status.HTTP_401_UNAUTHORIZED) response = self.client.create_policy(self.token, using=None) self.assertStatus(response, status.HTTP_401_UNAUTHORIZED) # Create ## without required field response = self.client.create_policy(self.token, using=self.token_manage) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data["domain"], ["This field is required."]) ## without a default policy data = dict(domain=self.my_domains[0].name) with transaction.atomic(): response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.data["domain"], ["Policy precedence: The first policy must be the default policy."], ) # List: still empty response = self.client.list_policies(self.token, using=self.token_manage) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, []) # Create ## default policy data = dict(domain=None, perm_rrsets=True) response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_201_CREATED) ## can't create another default policy with transaction.atomic(): response = self.client.create_policy( self.token, using=self.token_manage, data=dict(domain=None) ) self.assertStatus(response, status.HTTP_409_CONFLICT) ## verify object creation response = self.client.get_policy( self.token, using=self.token_manage, domain=None ) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, self.default_data | data) ## can't create policy for other user's domain data = dict(domain=self.other_domain.name, perm_dyndns=True, perm_rrsets=True) response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data["domain"][0].code, "does_not_exist") ## another policy data = dict(domain=self.my_domains[0].name, perm_dyndns=True) response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_201_CREATED) ## can't create policy for the same domain with transaction.atomic(): response = self.client.create_policy( self.token, using=self.token_manage, data=dict(domain=self.my_domains[0].name, perm_dyndns=False), ) self.assertStatus(response, status.HTTP_409_CONFLICT) ## verify object creation response = self.client.get_policy( self.token, using=self.token_manage, domain=self.my_domains[0].name ) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, self.default_data | data) # List: now has two elements response = self.client.list_policies(self.token, using=self.token_manage) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) # Change ## all fields of a policy data = dict(domain=self.my_domains[1].name, perm_dyndns=False, perm_rrsets=True) response = self.client.patch_policy( self.token, using=self.token_manage, domain=self.my_domains[0].name, data=data, ) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, self.default_data | data) ## verify modification response = self.client.get_policy( self.token, using=self.token_manage, domain=self.my_domains[1].name ) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, self.default_data | data) ## verify that policy for former domain is gone response = self.client.get_policy( self.token, using=self.token_manage, domain=self.my_domains[0].name ) self.assertStatus(response, status.HTTP_404_NOT_FOUND) ## verify that the default policy can't be changed to a non-default policy with transaction.atomic(): response = self.client.patch_policy( self.token, using=self.token_manage, domain=None, data=data ) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.data, { "domain": [ "Policy precedence: Cannot disable default policy when others exist." ] }, ) ## partially modify the default policy data = dict(perm_dyndns=True) response = self.client.patch_policy( self.token, using=self.token_manage, domain=None, data=data ) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, {"domain": None, "perm_rrsets": True} | data) # Delete ## can't delete default policy while others exist with transaction.atomic(): response = self.client.delete_policy( self.token, using=self.token_manage, domain=None ) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.data, { "domain": [ "Policy precedence: Can't delete default policy when there exist others." ] }, ) ## delete other policy response = self.client.delete_policy( self.token, using=self.token_manage, domain=self.my_domains[1].name ) self.assertStatus(response, status.HTTP_204_NO_CONTENT) ## delete default policy response = self.client.delete_policy( self.token, using=self.token_manage, domain=None ) self.assertStatus(response, status.HTTP_204_NO_CONTENT) ## idempotence: delete a non-existing policy response = self.client.delete_policy( self.token, using=self.token_manage, domain=self.my_domains[0].name ) self.assertStatus(response, status.HTTP_204_NO_CONTENT) ## verify that policies are gone for domain in [None, self.my_domains[0].name, self.my_domains[1].name]: response = self.client.get_policy( self.token, using=self.token_manage, domain=domain ) self.assertStatus(response, status.HTTP_404_NOT_FOUND) # List: empty again response = self.client.list_policies(self.token, using=self.token_manage) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, []) def test_policy_permissions(self): def _reset_policies(token): for policy in token.tokendomainpolicy_set.all(): for perm in self.default_data.keys(): setattr(policy, perm, False) policy.save() def _perform_requests(name, perm, value, **kwargs): responses = [] if value: pdns_name = self._normalize_name(name).lower() cm = self.assertPdnsNoRequestsBut( self.request_pdns_zone_update(name=pdns_name), self.request_pdns_zone_axfr(name=pdns_name), ) else: cm = nullcontext() if perm == "perm_dyndns": data = {"username": name, "password": self.token.plain} with cm: responses.append( self.client.get(self.reverse("v1:dyndns12update"), data) ) return responses if perm == "perm_rrsets": url_detail = self.reverse("v1:rrset@", name=name, subname="", type="A") url_list = self.reverse("v1:rrsets", name=name) responses.append(self.client.get(url_list, **kwargs)) responses.append(self.client.patch(url_list, [], **kwargs)) responses.append(self.client.put(url_list, [], **kwargs)) responses.append(self.client.post(url_list, [], **kwargs)) data = {"subname": "", "type": "A", "ttl": 3600, "records": ["1.2.3.4"]} with cm: responses += [ self.client.delete(url_detail, **kwargs), self.client.post(url_list, data=data, **kwargs), self.client.put(url_detail, data=data, **kwargs), self.client.patch(url_detail, data=data, **kwargs), self.client.get(url_detail, **kwargs), ] return responses raise ValueError(f"Unexpected permission: {perm}") # Create ## default policy data = dict(domain=None) response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_201_CREATED) ## another policy data = dict(domain=self.my_domains[0].name) response = self.client.create_policy( self.token, using=self.token_manage, data=data ) self.assertStatus(response, status.HTTP_201_CREATED) ## verify object creation response = self.client.get_policy( self.token, using=self.token_manage, domain=self.my_domains[0].name ) self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, self.default_data | data) policies = { self.my_domains[0]: self.token.tokendomainpolicy_set.get( domain__isnull=False ), self.my_domains[1]: self.token.tokendomainpolicy_set.get( domain__isnull=True ), } kwargs = dict(HTTP_AUTHORIZATION=f"Token {self.token.plain}") # For each permission type for perm in self.default_data.keys(): # For the domain with specific policy and for the domain covered by the default policy for domain in policies.keys(): # For both possible values of the permission for value in [True, False]: # Set only that permission for that domain (on its effective policy) _reset_policies(self.token) policy = policies[domain] setattr(policy, perm, value) policy.save() # Perform requests that test this permission and inspect responses for response in _perform_requests( domain.name, perm, value, **kwargs ): if value: self.assertIn(response.status_code, range(200, 300)) else: self.assertStatus(response, status.HTTP_403_FORBIDDEN) # Can't create domain data = {"name": self.random_domain_name()} response = self.client.post( self.reverse("v1:domain-list"), data, **kwargs ) self.assertStatus(response, status.HTTP_403_FORBIDDEN) # Can't access account details response = self.client.get(self.reverse("v1:account"), **kwargs) self.assertStatus(response, status.HTTP_403_FORBIDDEN) def test_domain_owner_consistency(self): models.TokenDomainPolicy(token=self.token, domain=None).save() domain = self.my_domains[0] policy = models.TokenDomainPolicy(token=self.token, domain=domain) policy.save() domain.owner = self.other_domains[0].owner with self.assertRaises(IntegrityError): with transaction.atomic(): # https://stackoverflow.com/a/23326971/6867099 domain.save() policy.delete() domain.save() def test_token_user_consistency(self): policy = models.TokenDomainPolicy(token=self.token, domain=None) policy.save() self.token.user = self.other_domains[0].owner with self.assertRaises(IntegrityError): with transaction.atomic(): # https://stackoverflow.com/a/23326971/6867099 self.token.save() policy.delete() self.token.save() def test_domain_owner_equals_token_user(self): models.TokenDomainPolicy(token=self.token, domain=None).save() with self.assertRaises(IntegrityError): with transaction.atomic(): # https://stackoverflow.com/a/23326971/6867099 models.TokenDomainPolicy( token=self.token, domain=self.other_domains[0] ).save() self.token.user = self.other_domain.owner with self.assertRaises(IntegrityError): with transaction.atomic(): # https://stackoverflow.com/a/23326971/6867099 self.token.save() def test_domain_deletion(self): domains = [None] + self.my_domains[:2] for domain in domains: models.TokenDomainPolicy(token=self.token, domain=domain).save() domain = domains.pop() domain.delete() self.assertEqual( list(map(lambda x: x.domain, self.token.tokendomainpolicy_set.all())), domains, ) def test_token_deletion(self): domains = [None] + self.my_domains[:2] policies = {} for domain in domains: policy = models.TokenDomainPolicy(token=self.token, domain=domain) policies[domain] = policy policy.save() self.token.delete() for domain, policy in policies.items(): self.assertFalse( models.TokenDomainPolicy.objects.filter(pk=policy.pk).exists() ) if domain: self.assertTrue(models.Domain.objects.filter(pk=domain.pk).exists()) def test_user_deletion(self): domains = [None] + self.my_domains[:2] for domain in domains: models.TokenDomainPolicy(token=self.token, domain=domain).save() # User can only be deleted when domains are deleted for domain in self.my_domains: domain.delete() # Only the default policy should be left, so get can simply get() it policy_pk = self.token.tokendomainpolicy_set.get().pk self.token.user.delete() self.assertFalse(models.TokenDomainPolicy.objects.filter(pk=policy_pk).exists())
mit
4afeb2e8371625f9ea01df36af967a2e
39.191837
98
0.597085
4.126126
false
false
false
false
desec-io/desec-stack
api/desecapi/views/tokens.py
1
3382
import django.core.exceptions from rest_framework import viewsets from rest_framework.exceptions import ValidationError from rest_framework.permissions import IsAuthenticated, SAFE_METHODS from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.views import APIView from desecapi import permissions from desecapi.models import TokenDomainPolicy from desecapi.serializers import TokenDomainPolicySerializer, TokenSerializer from .base import IdempotentDestroyMixin from .domains import DomainViewSet class TokenViewSet(IdempotentDestroyMixin, viewsets.ModelViewSet): serializer_class = TokenSerializer permission_classes = ( IsAuthenticated, permissions.IsAPIToken | permissions.MFARequiredIfEnabled, permissions.HasManageTokensPermission, ) throttle_scope = "account_management_passive" def get_queryset(self): return self.request.user.token_set.all() def get_serializer(self, *args, **kwargs): # When creating a new token, return the plaintext representation if self.action == "create": kwargs.setdefault("include_plain", True) return super().get_serializer(*args, **kwargs) def perform_create(self, serializer): serializer.save(user=self.request.user) class TokenPoliciesRoot(APIView): permission_classes = [ IsAuthenticated, permissions.IsAPIToken | permissions.MFARequiredIfEnabled, permissions.HasManageTokensPermission | permissions.AuthTokenCorrespondsToViewToken, ] def get(self, request, *args, **kwargs): return Response( { "domain": reverse( "token_domain_policies-list", request=request, kwargs=kwargs ) } ) class TokenDomainPolicyViewSet(IdempotentDestroyMixin, viewsets.ModelViewSet): lookup_field = "domain__name" lookup_value_regex = DomainViewSet.lookup_value_regex pagination_class = None serializer_class = TokenDomainPolicySerializer throttle_scope = "account_management_passive" @property def permission_classes(self): ret = [ IsAuthenticated, permissions.IsAPIToken | permissions.MFARequiredIfEnabled, ] if self.request.method in SAFE_METHODS: ret.append( permissions.HasManageTokensPermission | permissions.AuthTokenCorrespondsToViewToken ) else: ret.append(permissions.HasManageTokensPermission) return ret def dispatch(self, request, *args, **kwargs): # map default policy onto domain_id IS NULL lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field try: if kwargs[lookup_url_kwarg] == "default": kwargs[lookup_url_kwarg] = None except KeyError: pass return super().dispatch(request, *args, **kwargs) def get_queryset(self): return TokenDomainPolicy.objects.filter( token_id=self.kwargs["token_id"], token__user=self.request.user ) def perform_destroy(self, instance): try: super().perform_destroy(instance) except django.core.exceptions.ValidationError as exc: raise ValidationError(exc.message_dict, code="precedence")
mit
5009ecdda491fefb81405adb3d3ef774
33.510204
80
0.679184
4.52139
false
false
false
false
desec-io/desec-stack
api/desecapi/serializers/domains.py
1
6481
import dns.name import dns.zone from rest_framework import serializers from api import settings from desecapi.models import Domain, RR_SET_TYPES_AUTOMATIC from desecapi.validators import ReadOnlyOnUpdateValidator from .records import RRsetSerializer class DomainSerializer(serializers.ModelSerializer): default_error_messages = { **serializers.Serializer.default_error_messages, "name_unavailable": "This domain name conflicts with an existing zone, or is disallowed by policy.", } zonefile = serializers.CharField(write_only=True, required=False, allow_blank=True) class Meta: model = Domain fields = ( "created", "published", "name", "keys", "minimum_ttl", "touched", "zonefile", ) read_only_fields = ( "published", "minimum_ttl", ) extra_kwargs = { "name": {"trim_whitespace": False}, } def __init__(self, *args, include_keys=False, **kwargs): self.include_keys = include_keys self.import_zone = None super().__init__(*args, **kwargs) def get_fields(self): fields = super().get_fields() if not self.include_keys: fields.pop("keys") fields["name"].validators.append(ReadOnlyOnUpdateValidator()) return fields def validate_name(self, value): if not Domain(name=value, owner=self.context["request"].user).is_registrable(): raise serializers.ValidationError( self.default_error_messages["name_unavailable"], code="name_unavailable" ) return value def parse_zonefile(self, domain_name: str, zonefile: str): try: self.import_zone = dns.zone.from_text( zonefile, origin=dns.name.from_text(domain_name), allow_include=False, check_origin=False, relativize=False, ) except dns.zonefile.CNAMEAndOtherData: raise serializers.ValidationError( { "zonefile": [ "No other records with the same name are allowed alongside a CNAME record." ] } ) except ValueError as e: if "has non-origin SOA" in str(e): raise serializers.ValidationError( { "zonefile": [ f"Zonefile includes an SOA record for a name different from {domain_name}." ] } ) raise e except dns.exception.SyntaxError as e: try: line = str(e).split(":")[1] raise serializers.ValidationError( {"zonefile": [f"Zonefile contains syntax error in line {line}."]} ) except IndexError: raise serializers.ValidationError( {"zonefile": [f"Could not parse zonefile: {str(e)}"]} ) def validate(self, attrs): if attrs.get("zonefile") is not None: self.parse_zonefile(attrs.get("name"), attrs.pop("zonefile")) return super().validate(attrs) def create(self, validated_data): # save domain if ( "minimum_ttl" not in validated_data and Domain(name=validated_data["name"]).is_locally_registrable ): validated_data.update(minimum_ttl=60) domain: Domain = super().create(validated_data) # save RRsets if zonefile was given nodes = getattr(self.import_zone, "nodes", None) if nodes: zone_name = dns.name.from_text(validated_data["name"]) min_ttl, max_ttl = domain.minimum_ttl, settings.MAXIMUM_TTL data = [ { "type": dns.rdatatype.to_text(rrset.rdtype), "ttl": max(min_ttl, min(max_ttl, rrset.ttl)), "subname": (owner_name - zone_name).to_text() if owner_name - zone_name != dns.name.empty else "", "records": [rr.to_text() for rr in rrset], } for owner_name, node in nodes.items() for rrset in node.rdatasets if ( dns.rdatatype.to_text(rrset.rdtype) not in ( RR_SET_TYPES_AUTOMATIC | { # do not import automatically managed record types "CDS", "CDNSKEY", "DNSKEY", } # do not import these, as this would likely be unexpected ) and not ( owner_name - zone_name == dns.name.empty and rrset.rdtype == dns.rdatatype.NS ) # ignore apex NS ) ] rrset_list_serializer = RRsetSerializer( data=data, context=dict(domain=domain), many=True ) # The following line raises if data passed validation by dnspython during zone file parsing, # but is rejected by validation in RRsetSerializer. See also # test_create_domain_zonefile_import_validation try: rrset_list_serializer.is_valid(raise_exception=True) except serializers.ValidationError as e: if isinstance(e.detail, serializers.ReturnList): # match the order of error messages with the RRsets provided to the # serializer to make sense to the client def fqdn(idx): return (data[idx]["subname"] + "." + domain.name).lstrip(".") raise serializers.ValidationError( { "zonefile": [ f"{fqdn(idx)}/{data[idx]['type']}: {err}" for idx, d in enumerate(e.detail) for _, errs in d.items() for err in errs ] } ) raise e rrset_list_serializer.save() return domain
mit
e692409ffc78f864085194f0b1d337a0
36.680233
108
0.496683
4.779499
false
false
false
false
desec-io/desec-stack
api/desecapi/models/tokens.py
1
7834
from __future__ import annotations import ipaddress import secrets import uuid from datetime import timedelta import pgtrigger import rest_framework.authtoken.models from django.contrib.auth.hashers import make_password from django.contrib.postgres.fields import ArrayField from django.core import validators from django.core.exceptions import ValidationError from django.db import models, transaction from django.db.models import F, Q from django.utils import timezone from django_prometheus.models import ExportModelOperationsMixin from netfields import CidrAddressField, NetManager class Token(ExportModelOperationsMixin("Token"), rest_framework.authtoken.models.Token): @staticmethod def _allowed_subnets_default(): return [ipaddress.IPv4Network("0.0.0.0/0"), ipaddress.IPv6Network("::/0")] _validators = [ validators.MinValueValidator(timedelta(0)), validators.MaxValueValidator(timedelta(days=365 * 1000)), ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) key = models.CharField("Key", max_length=128, db_index=True, unique=True) user = models.ForeignKey("User", on_delete=models.CASCADE) name = models.CharField("Name", blank=True, max_length=64) last_used = models.DateTimeField(null=True, blank=True) mfa = models.BooleanField(default=None, null=True) perm_manage_tokens = models.BooleanField(default=False) allowed_subnets = ArrayField( CidrAddressField(), default=_allowed_subnets_default.__func__ ) max_age = models.DurationField(null=True, default=None, validators=_validators) max_unused_period = models.DurationField( null=True, default=None, validators=_validators ) domain_policies = models.ManyToManyField("Domain", through="TokenDomainPolicy") plain = None objects = NetManager() class Meta: constraints = [ models.UniqueConstraint(fields=["id", "user"], name="unique_id_user") ] @property def is_valid(self): now = timezone.now() # Check max age try: if self.created + self.max_age < now: return False except TypeError: pass # Check regular usage requirement try: if (self.last_used or self.created) + self.max_unused_period < now: return False except TypeError: pass return True def generate_key(self): self.plain = secrets.token_urlsafe(21) self.key = Token.make_hash(self.plain) return self.key @staticmethod def make_hash(plain): return make_password(plain, salt="static", hasher="pbkdf2_sha256_iter1") def get_policy(self, *, domain=None): order_by = F("domain").asc( nulls_last=True ) # default Postgres sorting, but: explicit is better than implicit return ( self.tokendomainpolicy_set.filter(Q(domain=domain) | Q(domain__isnull=True)) .order_by(order_by) .first() ) @transaction.atomic def delete(self): # This is needed because Model.delete() emulates cascade delete via django.db.models.deletion.Collector.delete() # which deletes related objects in pk order. However, the default policy has to be deleted last. # Perhaps this will change with https://code.djangoproject.com/ticket/21961 self.tokendomainpolicy_set.filter(domain__isnull=False).delete() self.tokendomainpolicy_set.filter(domain__isnull=True).delete() return super().delete() @pgtrigger.register( # Ensure that token_user is consistent with token pgtrigger.Trigger( name="token_user", operation=pgtrigger.Update | pgtrigger.Insert, when=pgtrigger.Before, func="NEW.token_user_id = (SELECT user_id FROM desecapi_token WHERE id = NEW.token_id); RETURN NEW;", ), # Ensure that if there is *any* domain policy for a given token, there is always one with domain=None. pgtrigger.Trigger( name="default_policy_on_insert", operation=pgtrigger.Insert, when=pgtrigger.Before, # Trigger `condition` arguments (corresponding to WHEN clause) don't support subqueries, so we use `func` func="IF (NEW.domain_id IS NOT NULL and NOT EXISTS(SELECT * FROM desecapi_tokendomainpolicy WHERE domain_id IS NULL AND token_id = NEW.token_id)) THEN " " RAISE EXCEPTION 'Cannot insert non-default policy into % table when default policy is not present', TG_TABLE_NAME; " "END IF; RETURN NEW;", ), pgtrigger.Protect( name="default_policy_on_update", operation=pgtrigger.Update, when=pgtrigger.Before, condition=pgtrigger.Q(old__domain__isnull=True, new__domain__isnull=False), ), # Ideally, a deferred trigger (https://github.com/Opus10/django-pgtrigger/issues/14). Available in 3.4.0. pgtrigger.Trigger( name="default_policy_on_delete", operation=pgtrigger.Delete, when=pgtrigger.Before, # Trigger `condition` arguments (corresponding to WHEN clause) don't support subqueries, so we use `func` func="IF (OLD.domain_id IS NULL and EXISTS(SELECT * FROM desecapi_tokendomainpolicy WHERE domain_id IS NOT NULL AND token_id = OLD.token_id)) THEN " " RAISE EXCEPTION 'Cannot delete default policy from % table when non-default policy is present', TG_TABLE_NAME; " "END IF; RETURN OLD;", ), ) class TokenDomainPolicy(ExportModelOperationsMixin("TokenDomainPolicy"), models.Model): token = models.ForeignKey(Token, on_delete=models.CASCADE) domain = models.ForeignKey("Domain", on_delete=models.CASCADE, null=True) perm_dyndns = models.BooleanField(default=False) perm_rrsets = models.BooleanField(default=False) # Token user, filled via trigger. Used by compound FK constraints to tie domain.owner to token.user (see migration). token_user = models.ForeignKey( "User", on_delete=models.CASCADE, db_constraint=False, related_name="+" ) class Meta: constraints = [ models.UniqueConstraint(fields=["token", "domain"], name="unique_entry"), models.UniqueConstraint( fields=["token"], condition=Q(domain__isnull=True), name="unique_entry_null_domain", ), ] def clean(self): default_policy = self.token.get_policy(domain=None) if self.pk: # update # Can't change policy's default status ("domain NULLness") to maintain policy precedence if (self.domain is None) != (self.pk == default_policy.pk): raise ValidationError( { "domain": "Policy precedence: Cannot disable default policy when others exist." } ) else: # create # Can't violate policy precedence (default policy has to be first) if (self.domain is not None) and (default_policy is None): raise ValidationError( { "domain": "Policy precedence: The first policy must be the default policy." } ) def delete(self, *args, **kwargs): # Can't delete default policy when others exist if (self.domain is None) and self.token.tokendomainpolicy_set.exclude( domain__isnull=True ).exists(): raise ValidationError( { "domain": "Policy precedence: Can't delete default policy when there exist others." } ) return super().delete(*args, **kwargs) def save(self, *args, **kwargs): self.clean() super().save(*args, **kwargs)
mit
8619b23b4395f2a6becba8279e028a65
39.802083
160
0.644498
4.125329
false
false
false
false
intel/intel-iot-refkit
meta-iotqa/lib/xmlrunner/runner.py
8
3949
import sys import time from .unittest import TextTestRunner from .result import _XMLTestResult # see issue #74, the encoding name needs to be one of # http://www.iana.org/assignments/character-sets/character-sets.xhtml UTF8 = 'UTF-8' class XMLTestRunner(TextTestRunner): """ A test runner class that outputs the results in JUnit like XML files. """ def __init__(self, output='.', outsuffix=None, stream=sys.stderr, descriptions=True, verbosity=1, elapsed_times=True, failfast=False, buffer=False, encoding=UTF8, resultclass=None): TextTestRunner.__init__(self, stream, descriptions, verbosity, failfast=failfast, buffer=buffer) self.verbosity = verbosity self.output = output self.encoding = encoding # None means default timestamped suffix # '' (empty) means no suffix if outsuffix is None: outsuffix = time.strftime("%Y%m%d%H%M%S") self.outsuffix = outsuffix self.elapsed_times = elapsed_times if resultclass is None: self.resultclass = _XMLTestResult else: self.resultclass = resultclass def _make_result(self): """ Creates a TestResult object which will be used to store information about the executed tests. """ # override in subclasses if necessary. return self.resultclass( self.stream, self.descriptions, self.verbosity, self.elapsed_times ) def run(self, test): """ Runs the given test case or test suite. """ try: # Prepare the test execution result = self._make_result() result.failfast = self.failfast if hasattr(test, 'properties'): # junit testsuite properties result.properties = test.properties # Print a nice header self.stream.writeln() self.stream.writeln('Running tests...') self.stream.writeln(result.separator2) # Execute tests start_time = time.time() test(result) stop_time = time.time() time_taken = stop_time - start_time # Print results result.printErrors() self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % ( run, run != 1 and "s" or "", time_taken) ) self.stream.writeln() # other metrics expectedFails = len(result.expectedFailures) unexpectedSuccesses = len(result.unexpectedSuccesses) skipped = len(result.skipped) # Error traces infos = [] if not result.wasSuccessful(): self.stream.write("FAILED") failed, errored = map(len, (result.failures, result.errors)) if failed: infos.append("failures={0}".format(failed)) if errored: infos.append("errors={0}".format(errored)) else: self.stream.write("OK") if skipped: infos.append("skipped={0}".format(skipped)) if expectedFails: infos.append("expected failures={0}".format(expectedFails)) if unexpectedSuccesses: infos.append("unexpected successes={0}".format( unexpectedSuccesses)) if infos: self.stream.writeln(" ({0})".format(", ".join(infos))) else: self.stream.write("\n") # Generate reports self.stream.writeln() self.stream.writeln('Generating XML reports...') result.generate_reports(self) finally: pass return result
mit
8f20502ba1f9fea95f248563bf301d90
33.043103
78
0.549759
4.70119
false
true
false
false
stxnext-csr/volontulo
setup.py
6
1767
# -*- coding: utf-8 -*- u""" .. module:: setup """ import os from distutils.command.install import install from setuptools import setup from subprocess import check_output REPO_ROOT = os.path.dirname(__file__) class install_with_gulp(install): u"""Class extending install command - responsible for building fronted.""" def run(self): u"""Definition of custom install command.""" check_output( ['npm', 'install', '--quiet'], cwd=os.path.join(REPO_ROOT, 'volontulo'), ) check_output( ['gulp', 'build'], cwd=os.path.join(REPO_ROOT, 'volontulo') ) install.run(self) with open(os.path.join(REPO_ROOT, 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='volontulo', version='alpha', packages=['apps.volontulo'], include_package_data=True, license='MIT License', description='Simple Django app connecting organizations with volonteers.', long_description=README, cmdclass=dict(install=install_with_gulp), url='http://volontuloapp.org/', author='Tomasz Magulski', author_email='tomasz.magulski@stxnext.pl', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
mit
35d19931744a877c865badebb6039033
28.45
78
0.617997
3.759574
false
false
false
false
lilydjwg/nvchecker
tests/test_regex.py
1
4336
# MIT licensed # Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al. import base64 import pytest import pytest_httpbin assert pytest_httpbin # for pyflakes pytestmark = pytest.mark.asyncio def base64_encode(s): return base64.b64encode(s.encode('utf-8')).decode('ascii') async def test_regex_httpbin_default_user_agent(get_version, httpbin): ua = await get_version("example", { "source": "regex", "url": httpbin.url + "/get", "regex": r'"User-Agent":\s*"([^"]+)"', }) assert ua.startswith("lilydjwg/nvchecker") async def test_regex_httpbin_user_agent(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/get", "regex": r'"User-Agent":\s*"(\w+)"', "user_agent": "Meow", }) == "Meow" async def test_regex(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/base64/" + base64_encode("version 1.12 released"), "regex": r'version ([0-9.]+)', }) == "1.12" async def test_missing_ok(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/base64/" + base64_encode("something not there"), "regex": "foobar", "missing_ok": True, }) is None async def test_missing(get_version, httpbin): with pytest.raises(RuntimeError): await get_version("example", { "source": "regex", "url": httpbin.url + "/base64/" + base64_encode("something not there"), "regex": "foobar", }) async def test_multi_group(get_version, httpbin): with pytest.raises(RuntimeError): await get_version("example", { "source": "regex", "url": httpbin.url + "/base64/" + base64_encode("1.2"), "regex": r"(\d+)\.(\d+)", }) async def test_regex_with_tokenBasic(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/basic-auth/username/superpassword", "httptoken": "Basic dXNlcm5hbWU6c3VwZXJwYXNzd29yZA==", "regex": r'"user":"([a-w]+)"', }) == "username" async def test_regex_with_tokenBearer(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/bearer", "httptoken": "Bearer username:password", "regex": r'"token":"([a-w]+):.*"', }) == "username" async def test_regex_no_verify_ssl(get_version, httpbin_secure): assert await get_version("example", { "source": "regex", "url": httpbin_secure.url + "/base64/" + base64_encode("version 1.12 released"), "regex": r'version ([0-9.]+)', "verify_cert": False, }) == "1.12" async def test_regex_bad_ssl(get_version, httpbin_secure): try: await get_version("example", { "source": "regex", "url": httpbin_secure.url + "/base64/" + base64_encode("version 1.12 released"), "regex": r'version ([0-9.]+)', }) except Exception: pass else: assert False, 'certificate should not be trusted' async def test_regex_post(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/post", "regex": r'"ABCDEF":\s*"(\w+)"', "post_data": "ABCDEF=234&CDEFG=xyz" }) == "234" async def test_regex_post2(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/post", "regex": r'"CDEFG":\s*"(\w+)"', "post_data": "ABCDEF=234&CDEFG=xyz" }) == "xyz" async def test_regex_post_json(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/post", "regex": r'"ABCDEF":\s*(\w+)', "post_data": '{"ABCDEF":234,"CDEFG":"xyz"}', "post_data_type": "application/json" }) == "234" async def test_regex_post_json2(get_version, httpbin): assert await get_version("example", { "source": "regex", "url": httpbin.url + "/post", "regex": r'"CDEFG":\s*"(\w+)"', "post_data": '{"ABCDEF":234,"CDEFG":"xyz"}', "post_data_type": "application/json" }) == "xyz"
mit
83b3293d8708092f12210a9fa466be31
32.353846
92
0.566882
3.243082
false
true
false
false
lilydjwg/nvchecker
nvchecker_source/htmlparser.py
1
1215
# MIT licensed # Copyright (c) 2020 Ypsilik <tt2laurent.maud@gmail.com>, et al. # Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al. from lxml import html, etree from nvchecker.api import session, GetVersionError async def get_version(name, conf, *, cache, **kwargs): key = tuple(sorted(conf.items())) return await cache.get(key, get_version_impl) async def get_version_impl(info): conf = dict(info) encoding = conf.get('encoding') parser = html.HTMLParser(encoding=encoding) data = conf.get('post_data') if data is None: res = await session.get(conf['url']) else: res = await session.post(conf['url'], body = data, headers = { 'Content-Type': conf.get('post_data_type', 'application/x-www-form-urlencoded') }) doc = html.fromstring(res.body, base_url=conf['url'], parser=parser) try: els = doc.xpath(conf.get('xpath')) except ValueError: if not conf.get('missing_ok', False): raise GetVersionError('version string not found.') except etree.XPathEvalError as e: raise GetVersionError('bad xpath', exc_info=e) version = [ str(el) if isinstance(el, str) else str(el.text_content()) for el in els ] return version
mit
8a21cf3c4144a78071cf18cf4923d4ef
28.634146
87
0.674074
3.257373
false
false
false
false
stxnext-csr/volontulo
apps/volontulo/tests/views/offers/test_offer_join.py
2
6957
# -*- coding: utf-8 -*- u""" .. module:: test_offer_join """ from django.contrib.auth.models import User from django.test import Client from django.test import TestCase from apps.volontulo.models import Offer from apps.volontulo.models import Organization from apps.volontulo.models import UserProfile class TestOffersJoin(TestCase): """Class responsible for testing offer's join page.""" @classmethod def setUpTestData(cls): """Set up data for all tests.""" organization = Organization.objects.create( name='Organization Name', address='', description='', ) organization.save() cls.offer = Offer.objects.create( organization=organization, description='', requirements='', time_commitment='', benefits='', location='', title='volontulo offer', time_period='', status_old='NEW', started_at='2015-10-10 21:22:23', finished_at='2015-12-12 11:12:13', ) cls.offer.save() cls.volunteer = User.objects.create_user( 'volunteer@example.com', 'volunteer@example.com', 'vol123', ) cls.volunteer.save() cls.volunteer_profile = UserProfile(user=cls.volunteer) cls.volunteer_profile.save() def setUp(self): """Set up each test.""" self.client = Client() def test_for_nonexisting_offer(self): """Test if error 404 will be raised when offer dosn't exist.""" response = self.client.get('/offers/some-slug/42/join') self.assertEqual(response.status_code, 404) def test_for_different_slug(self): """Test if redirect will be raised when offer has different slug.""" response = self.client.get('/offers/different-slug/{}/join'.format( self.offer.id )) self.assertRedirects( response, '/offers/volontulo-offer/{}/join'.format(self.offer.id), 302, 200, ) def test_correct_slug_for_anonymous_user(self): """Test get method of offer join for anonymous user.""" response = self.client.get('/offers/volontulo-offer/{}/join'.format( self.offer.id )) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'offers/offer_apply.html') self.assertIn('offer', response.context) self.assertIn('volunteer_user', response.context) self.assertEqual(response.context['volunteer_user'].pk, None) def test_correct_slug_for_logged_in_user(self): """Test get method of offer join for logged in user.""" self.client.post('/login', { 'email': 'volunteer@example.com', 'password': 'vol123', }) response = self.client.get('/offers/volontulo-offer/{}/join'.format( self.offer.id )) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'offers/offer_apply.html') self.assertIn('offer', response.context) self.assertIn('volunteer_user', response.context) self.assertEqual(response.context['volunteer_user'].pk, self.volunteer_profile.id) self.assertContains(response, 'volunteer@example.com') def test_offers_join_invalid_form(self): """Test attempt of joining offer with invalid form.""" response = self.client.post('/offers/volontulo-offer/{}/join'.format( self.offer.id ), {}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'offers/offer_apply.html') self.assertContains( response, 'Formularz zawiera nieprawidłowe dane', ) def test_offers_join_valid_form_and_logged_user(self): """Test attempt of joining offer with valid form and logged user.""" self.client.post('/login', { 'email': 'volunteer@example.com', 'password': 'vol123', }) # successfull joining offer: response = self.client.post('/offers/volontulo-offer/{}/join'.format( self.offer.id ), { 'email': 'volunteer@example.com', 'phone_no': '+42 42 42 42', 'fullname': 'Mister Volunteer', 'comments': 'Some important staff.', }, follow=True) self.assertRedirects( response, '/offers/volontulo-offer/{}'.format(self.offer.id), 302, 200, ) # unsuccessfull joining the same offer for the second time: response = self.client.post('/offers/volontulo-offer/{}/join'.format( self.offer.id ), { 'email': 'volunteer@example.com', 'phone_no': '+42 42 42 42', 'fullname': 'Mister Volunteer', 'comments': 'Some important staff.', }, follow=True) self.assertRedirects( response, '/offers', 302, 200, ) self.assertContains( response, 'Już wyraziłeś chęć uczestnictwa w tej ofercie.', ) def test_offers_join_valid_form_and_anonymous_user(self): """Test attempt of joining offer with valid form and anon user.""" post_data = { 'email': 'anon@example.com', 'phone_no': '+42 42 42 42', 'fullname': 'Mister Anonymous', 'comments': 'Some important staff.', } # successfull joining offer: response = self.client.post( '/offers/volontulo-offer/{}/join'.format(self.offer.id), post_data, follow=True, ) self.assertRedirects( response, '/register', 302, 200, ) self.assertContains( response, 'Zarejestruj się, aby zapisać się do oferty.', ) def test_offers_join_valid_form_with_existing_email(self): """Test attempt of joining offer with valid form and existing email.""" post_data = { 'email': 'volunteer@example.com', 'phone_no': '+42 42 42 42', 'fullname': 'Mister Anonymous', 'comments': 'Some important staff.', } # successfull joining offer: response = self.client.post( '/offers/volontulo-offer/{}/join'.format(self.offer.id), post_data, follow=True, ) self.assertRedirects( response, '/login?next=/offers/volontulo-offer/{}/join'.format( self.offer.id ), 302, 200, ) self.assertContains( response, 'Zaloguj się, aby zapisać się do oferty.', )
mit
05ecb093bb61641c3d6029865da87aef
32.229665
79
0.555508
4.107037
false
true
false
false
ni/nixnet-python
nixnet/_frames.py
2
5893
from __future__ import absolute_import from __future__ import division from __future__ import print_function import struct from nixnet import _cconsts from nixnet import _errors from nixnet import constants from nixnet import types nxFrameFixed_t = struct.Struct('QIBBBB8s') # NOQA: N801 assert nxFrameFixed_t.size == 24, 'Incorrectly specified frame.' FRAME_TIMESTAMP_INDEX = 0 FRAME_IDENTIFIER_INDEX = 1 FRAME_TYPE_INDEX = 2 FRAME_FLAG_INDEX = 3 FRAME_INFO_INDEX = 4 FRAME_PAYLOAD_LENGTH_INDEX = 5 FRAME_PAYLOAD_INDEX = 6 MAX_BASE_UNIT_PAYLOAD_LENGTH = 8 def _get_frame_payload_length(base): """Extract the payload length from a base unit. >>> blank_payload = 8 * b'\\0' >>> no_payload = nxFrameFixed_t.unpack(nxFrameFixed_t.pack(0, 0, 0, 0, 0, 0x0, blank_payload)) >>> _get_frame_payload_length(no_payload) 0 >>> base_payload = nxFrameFixed_t.unpack(nxFrameFixed_t.pack(0, 0, 0, 0, 0, 0x8, blank_payload)) >>> _get_frame_payload_length(base_payload) 8 >>> extra_payload = nxFrameFixed_t.unpack(nxFrameFixed_t.pack(0, 0, 0, 0, 0, 0xFF, blank_payload)) >>> _get_frame_payload_length(extra_payload) 255 >>> j1939_type = _cconsts.NX_FRAME_TYPE_J1939_DATA >>> j1939 = nxFrameFixed_t.unpack(nxFrameFixed_t.pack(0, 0, j1939_type, 0, 0xFF, 0xFF, blank_payload)) >>> _get_frame_payload_length(j1939) 2047 """ payload_length = base[FRAME_PAYLOAD_LENGTH_INDEX] if base[FRAME_TYPE_INDEX] == _cconsts.NX_FRAME_TYPE_J1939_DATA: # J1939 uses three bits from the Info field as the high bites. payload_length |= (base[FRAME_INFO_INDEX] & _cconsts.NX_FRAME_PAYLD_LEN_HIGH_MASK_J1939) << 8 return payload_length def _calculate_payload_size(payload_length): """For a given payload, return the bytes needed for the payload. This is for the entire payload with padding, regardless of which unit it is stored in. >>> _calculate_payload_size(0) 8 >>> _calculate_payload_size(8) 8 >>> _calculate_payload_size(9) 16 >>> _calculate_payload_size(16) 16 """ if 8 < payload_length: return (payload_length + 7) & 0x07F8 else: return 8 def _calculate_payload_unit_size(payload_length): """For a given payload, return the bytes needed for the payload unit. This includes padding bytes >>> _calculate_payload_unit_size(0) 0 >>> _calculate_payload_unit_size(8) 0 >>> _calculate_payload_unit_size(9) 8 >>> _calculate_payload_unit_size(16) 8 """ return _calculate_payload_size(payload_length) - MAX_BASE_UNIT_PAYLOAD_LENGTH def _split_payload_length(payload_length): """Return how much of the payload is stored in the base unit verse the payload unit. This is without padding bytes. >>> _split_payload_length(0) (0, 0) >>> _split_payload_length(8) (8, 0) >>> _split_payload_length(9) (8, 1) >>> _split_payload_length(16) (8, 8) """ payload_unit_length = max(payload_length - MAX_BASE_UNIT_PAYLOAD_LENGTH, 0) base_unit_length = payload_length - payload_unit_length return base_unit_length, payload_unit_length def iterate_frames(bytes): """Yields RawFrames from the bytes""" base_pos = 0 next_pos = base_pos while next_pos != len(bytes): base_pos = next_pos next_pos += nxFrameFixed_t.size if len(bytes) < next_pos: _errors.check_for_error(_cconsts.NX_ERR_INTERNAL_ERROR) raw_base = bytes[base_pos:next_pos] base_unit = nxFrameFixed_t.unpack(raw_base) payload_length = _get_frame_payload_length(base_unit) base_unit_length, payload_unit_length = _split_payload_length(payload_length) payload_pos = next_pos payload_pad_pos = payload_pos + payload_unit_length next_pos += _calculate_payload_unit_size(payload_length) base_unit_payload = base_unit[FRAME_PAYLOAD_INDEX][0:base_unit_length] payload_unit = bytes[payload_pos:payload_pad_pos] payload = base_unit_payload + payload_unit yield types.RawFrame( base_unit[FRAME_TIMESTAMP_INDEX], base_unit[FRAME_IDENTIFIER_INDEX], constants.FrameType(base_unit[FRAME_TYPE_INDEX]), base_unit[FRAME_FLAG_INDEX], base_unit[FRAME_INFO_INDEX], payload) def serialize_frame(frame): """Yields units that compose the frame.""" payload = bytes(frame.payload) base_unit_payload = payload[0:MAX_BASE_UNIT_PAYLOAD_LENGTH] base_unit_padding_length = max(MAX_BASE_UNIT_PAYLOAD_LENGTH - len(base_unit_payload), 0) base_unit_payload += b'\0' * base_unit_padding_length payload_unit = payload[MAX_BASE_UNIT_PAYLOAD_LENGTH:] payload_unit_padding_length = _calculate_payload_unit_size(len(payload)) - len(payload_unit) payload_unit += b'\0' * payload_unit_padding_length payload_length = len(payload) if frame.type == constants.FrameType.J1939_DATA: if (frame.info & _cconsts.NX_FRAME_PAYLD_LEN_HIGH_MASK_J1939) != 0: # Invalid data where info_length will go. _errors.check_for_error(_cconsts.NX_ERR_INTERNAL_ERROR) info_length = payload_length >> 8 if info_length != (info_length & _cconsts.NX_FRAME_PAYLD_LEN_HIGH_MASK_J1939): _errors.check_for_error(_cconsts.NX_ERR_FRAME_WRITE_TOO_LARGE) info = frame.info | info_length payload_length &= 0xFF else: if payload_length != (payload_length & 0xFF): _errors.check_for_error(_cconsts.NX_ERR_NON_J1939_FRAME_SIZE) info = frame.info base_unit = nxFrameFixed_t.pack( frame.timestamp, frame.identifier, frame.type.value, frame.flags, info, payload_length, base_unit_payload) yield base_unit if payload_unit: yield payload_unit
mit
eb1639cbc70d7e5e0b9bda2e83bf6176
32.482955
106
0.649584
3.325621
false
false
false
false
ni/nixnet-python
nixnet_examples/can_frame_queued_io.py
1
3364
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import six import nixnet from nixnet import constants from nixnet import types def main(): database_name = 'NIXNET_example' cluster_name = 'CAN_Cluster' input_frame = 'CANEventFrame1' output_frame = 'CANEventFrame1' interface1 = 'CAN1' interface2 = 'CAN2' with nixnet.FrameInQueuedSession( interface1, database_name, cluster_name, input_frame) as input_session: with nixnet.FrameOutQueuedSession( interface2, database_name, cluster_name, output_frame) as output_session: terminated_cable = six.moves.input('Are you using a terminated cable (Y or N)? ') if terminated_cable.lower() == "y": input_session.intf.can_term = constants.CanTerm.ON output_session.intf.can_term = constants.CanTerm.OFF elif terminated_cable.lower() == "n": input_session.intf.can_term = constants.CanTerm.ON output_session.intf.can_term = constants.CanTerm.ON else: print("Unrecognised input ({}), assuming 'n'".format(terminated_cable)) input_session.intf.can_term = constants.CanTerm.ON output_session.intf.can_term = constants.CanTerm.ON # Start the input session manually to make sure that the first # frame value sent before the initial read will be received. input_session.start() user_value = six.moves.input('Enter payload [int, int]: ') try: payload_list = [int(x.strip()) for x in user_value.split(",")] except ValueError: payload_list = [2, 4, 8, 16] print('Unrecognized input ({}). Setting data buffer to {}'.format(user_value, payload_list)) id = types.CanIdentifier(0) payload = bytearray(payload_list) frame = types.CanFrame(id, constants.FrameType.CAN_DATA, payload) i = 0 while True: for index, byte in enumerate(payload): payload[index] = byte + i frame.payload = payload output_session.frames.write([frame]) print('Sent frame with ID: {} payload: {}'.format(frame.identifier, list(frame.payload))) # Wait 1 s and then read the received values. # They should be the same as the ones sent. time.sleep(1) count = 1 frames = input_session.frames.read(count) for frame in frames: print('Received frame with ID: {} payload: {}'.format(frame.identifier, list(six.iterbytes(frame.payload)))) i += 1 if max(payload) + i > 0xFF: i = 0 inp = six.moves.input('Hit enter to continue (q to quit): ') if inp.lower() == 'q': break print('Data acquisition stopped.') if __name__ == '__main__': main()
mit
b8b4d0391002e3b79e559a435771e87f
35.967033
110
0.52824
4.503347
false
false
false
false
ni/nixnet-python
docs/conf.py
1
5720
# -*- coding: utf-8 -*- # # NI-XNET Python API documentation build configuration file, created by # sphinx-quickstart on Thu Jun 14 09:40:36 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # from datetime import datetime import os import re import sys sys.path.insert(0, os.path.abspath('../')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'nixnet' author = u'National Instruments' copyright = u'2017-{}, {}'.format(datetime.now().year, author) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. def get_version(): """ Gets the version stored in the VERSION file updated by the build. Returns: str: The version stored in the packages VERSION file. """ script_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) script_dir = os.path.join(script_dir, project) with open(os.path.join(script_dir, "VERSION"), "r") as version_file: version = version_file.read().rstrip() return version def get_short_version(): """ Gets the short version (X.Y) for this package. Returns: str: The short version of this package. """ version = get_version() m = re.search(r"(^\d+\.\d+)", version) return m.groups(1)[0] # The short X.Y version. version = get_short_version() # The full version, including alpha/beta/rc tags. release = get_version() # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'NI-XNETPythonAPIdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'NI-XNETPythonAPI.tex', u'NI-XNET Python API Documentation', u'National Instruments', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'ni-xnetpythonapi', u'NI-XNET Python API Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'NI-XNETPythonAPI', u'NI-XNET Python API Documentation', author, 'NI-XNETPythonAPI', 'One line description of project.', 'Miscellaneous'), ]
mit
6e7d615813d1c614b1057dd024849d97
30.086957
79
0.668007
3.872715
false
true
false
false
ni/nixnet-python
nixnet/types.py
1
35486
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import typing # NOQA: F401 import six from nixnet import _cconsts from nixnet import _errors from nixnet import _py2 from nixnet import constants __all__ = [ 'DriverVersion', 'CanComm', 'LinComm', 'CanIdentifier', 'FrameFactory', 'Frame', 'RawFrame', 'CanFrame', 'CanBusErrorFrame', 'LinFrame', 'LinBusErrorFrame', 'DelayFrame', 'LogTriggerFrame', 'StartTriggerFrame', 'XnetFrame', 'PduProperties'] DriverVersion_ = collections.namedtuple( 'DriverVersion_', ['major', 'minor', 'update', 'phase', 'build']) class DriverVersion(DriverVersion_): """Driver Version The arguments align with the following fields: ``[major].[minor].[update][phase][build]``. Attributes: major (int): minor (int): update (int): phase (:any:`nixnet._enums.Phase`): build (int): """ CanComm_ = collections.namedtuple( 'CanComm_', ['state', 'tcvr_err', 'sleep', 'last_err', 'tx_err_count', 'rx_err_count']) class CanComm(CanComm_): """CAN Communication State. Attributes: state (:any:`nixnet._enums.CanCommState`): Communication State tcvr_err (bool): Transceiver Error. Transceiver error indicates whether an error condition exists on the physical transceiver. This is typically referred to as the transceiver chip NERR pin. False indicates normal operation (no error), and true indicates an error. sleep (bool): Sleep. Sleep indicates whether the transceiver and communication controller are in their sleep state. False indicates normal operation (awake), and true indicates sleep. last_err (:any:`nixnet._enums.CanLastErr`): Last Error. Last error specifies the status of the last attempt to receive or transmit a frame tx_err_count (int): Transmit Error Counter. The transmit error counter begins at 0 when communication starts on the CAN interface. The counter increments when an error is detected for a transmitted frame and decrements when a frame transmits successfully. The counter increases more for an error than it is decreased for success. This ensures that the counter generally increases when a certain ratio of frames (roughly 1/8) encounter errors. When communication state transitions to Bus Off, the transmit error counter no longer is valid. rx_err_count (int): Receive Error Counter. The receive error counter begins at 0 when communication starts on the CAN interface. The counter increments when an error is detected for a received frame and decrements when a frame is received successfully. The counter increases more for an error than it is decreased for success. This ensures that the counter generally increases when a certain ratio of frames (roughly 1/8) encounter errors. """ pass LinComm_ = collections.namedtuple( 'LinComm_', ['sleep', 'state', 'last_err', 'err_received', 'err_expected', 'err_id', 'tcvr_rdy', 'sched_index']) class LinComm(LinComm_): """CAN Communication State. Attributes: sleep (bool): Sleep. Indicates whether the transceiver and communication controller are in their sleep state. False indicates normal operation (awake), and true indicates sleep. state (:any:`nixnet._enums.LinCommState`): Communication State last_err (:any:`nixnet._enums.LinLastErr`): Last Error. Last error specifies the status of the last attempt to receive or transmit a frame err_received (int): Returns the value received from the network when last error occurred. When ``last_err`` is ``READBACK``, this is the value read back. When ``last_err`` is ``CHECKSUM``, this is the received checksum. err_expected (int): Returns the value that the LIN interface expected to see (instead of last received). When ``last_err`` is ``READBACK``, this is the value transmitted. When ``last_err`` is ``CHECKSUM``, this is the calculated checksum. err_id (int): Returns the frame identifier in which the last error occurred. This is not applicable when ``last_err`` is ``NONE`` or ``UNKNOWN_ID``. tcvr_rdy (bool): Indicates whether the LIN transceiver is powered from the bus. True indicates the bus power exists, so it is safe to start communication on the LIN interface. If this value is false, you cannot start communication successfully. Wire power to the LIN transceiver and run your application again. sched_index (int): Indicates the LIN schedule that the interface currently is running. This index refers to a LIN schedule that you requested using the :any:`nixnet._session.base.SessionBase.change_lin_schedule` function. It indexes the array of schedules represented in the :any:`nixnet._session.intf.Interface.lin_sched_names`. This index applies only when the LIN interface is running as a master. If the LIN interface is running as a slave only, this element should be ignored. """ pass PduProperties_ = collections.namedtuple( 'PDU_PROPERTIES_', ['pdu', 'start_bit', 'update_bit']) class PduProperties(PduProperties_): """Properties that map a PDU onto a frame. Mapping PDUs to a frame requires setting three frame properties that are combined into this tuple. Attributes: pdu (:any:`Pdu`): Defines the sequence of values for the other two properties. start_bit (int): Defines the start bit of the PDU inside the frame. update_bit (int): Defines the update bit for the PDU inside the frame. If the update bit is not used, set the value to ``-1``. """ class CanIdentifier(object): """CAN frame arbitration identifier. Attributes: identifier(int): CAN frame arbitration identifier extended(bool): If the identifier is extended """ _FRAME_ID_MASK = 0x000007FF _EXTENDED_FRAME_ID_MASK = 0x1FFFFFFF def __init__(self, identifier, extended=False): # type: (int, bool) -> None self.identifier = identifier self.extended = extended @classmethod def from_raw(cls, raw): # type: (int) -> CanIdentifier """Parse a raw frame identifier into a CanIdentifier Args: raw(int): A raw frame identifier Returns: CanIdentifier: parsed value >>> CanIdentifier.from_raw(0x1) CanIdentifier(0x1) >>> CanIdentifier.from_raw(0x20000001) CanIdentifier(0x1, extended=True) """ extended = bool(raw & _cconsts.NX_FRAME_ID_CAN_IS_EXTENDED) if extended: identifier = raw & cls._EXTENDED_FRAME_ID_MASK else: identifier = raw & cls._FRAME_ID_MASK return cls(identifier, extended) def __int__(self): """Convert CanIdentifier into a raw frame identifier >>> hex(int(CanIdentifier(1))) '0x1' >>> hex(int(CanIdentifier(1, True))) '0x20000001' """ identifier = self.identifier if self.extended: if identifier != (identifier & self._EXTENDED_FRAME_ID_MASK): _errors.check_for_error(_cconsts.NX_ERR_UNDEFINED_FRAME_ID) identifier |= _cconsts.NX_FRAME_ID_CAN_IS_EXTENDED else: if identifier != (identifier & self._FRAME_ID_MASK): _errors.check_for_error(_cconsts.NX_ERR_UNDEFINED_FRAME_ID) return identifier def __eq__(self, other): if isinstance(other, CanIdentifier): other_id = typing.cast(CanIdentifier, other) return all(( self.identifier == other_id.identifier, self.extended == other_id.extended)) else: return NotImplemented def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result else: return not result def __repr__(self): """CanIdentifier debug representation. >>> CanIdentifier(1) CanIdentifier(0x1) >>> CanIdentifier(1, True) CanIdentifier(0x1, extended=True) """ if self.extended: return "{}(0x{:x}, extended={})".format( type(self).__name__, self.identifier, self.extended) else: return "{}(0x{:x})".format( type(self).__name__, self.identifier) @six.add_metaclass(abc.ABCMeta) class FrameFactory(object): """ABC for creating :any:`nixnet.types.Frame` objects.""" __slots__ = () @_py2.abstractclassmethod def from_raw(cls, frame): # NOQA: N805 can't detect abstractclassmethod # No type annotation because mypy doesn't understand # abstractclassmethod is the same as classmethod """Convert from RawFrame.""" pass @six.add_metaclass(abc.ABCMeta) class Frame(FrameFactory): """ABC for frame objects.""" __slots__ = () @abc.abstractmethod def to_raw(self): # type: () -> RawFrame """Convert to RawFrame.""" pass @abc.abstractproperty def type(self): # type: () -> constants.FrameType """:any:`nixnet._enums.FrameType`: Frame format.""" pass @abc.abstractmethod def __eq__(self, other): pass def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result else: return not result @abc.abstractmethod def __repr__(self): pass class RawFrame(Frame): """Raw Frame. Attributes: timestamp(int): Absolute time the XNET interface received the end-of-frame. identifier(int): Frame identifier. type(:any:`nixnet._enums.FrameType`): Frame type. flags(int): Flags that qualify the type. info(int): Info that qualify the type. payload(bytes): Payload. """ __slots__ = [ "timestamp", "identifier", "_type", "flags", "info", "payload"] def __init__(self, timestamp, identifier, type, flags=0, info=0, payload=b""): # type: (int, int, constants.FrameType, int, int, bytes) -> None self.timestamp = timestamp self.identifier = identifier self._type = type self.flags = flags self.info = info self.payload = payload @classmethod def from_raw(cls, frame): """Convert from RawFrame.""" return frame def to_raw(self): """Convert to RawFrame.""" return self @property def type(self): return self._type def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(RawFrame, other) return all(( self.timestamp == other_frame.timestamp, self.identifier == other_frame.identifier, self.type == other_frame.type, self.flags == other_frame.flags, self.info == other_frame.info, self.payload == other_frame.payload)) else: return NotImplemented def __repr__(self): # type: () -> typing.Text """RawFrame debug representation. >>> RawFrame(1, 2, constants.FrameType.CAN_DATA, 3, 4) RawFrame(timestamp=0x1, identifier=0x2, type=FrameType.CAN_DATA, flags=0x3, info=0x4) """ optional = [] if self.flags != 0: optional.append('flags=0x{:x}'.format(self.flags)) if self.info != 0: optional.append('info=0x{:x}'.format(self.info)) if self.payload: optional.append('len(payload)={}'.format(len(self.payload))) if optional: optional_params = ', {}'.format(", ".join(optional)) else: optional_params = '' return "{}(timestamp=0x{:x}, identifier=0x{:x}, type={}{})".format( type(self).__name__, self.timestamp, self.identifier, self.type, optional_params) class CanFrame(Frame): """CAN Frame. Attributes: identifier(:any:`nixnet.types.CanIdentifier`): CAN frame arbitration identifier. echo(bool): If the frame is an echo of a successful transmit rather than being received from the network. type(:any:`nixnet._enums.FrameType`): Frame type. timestamp(int): Absolute time the XNET interface received the end-of-frame. payload(bytes): Payload. """ __slots__ = [ "identifier", "echo", "_type", "timestamp", "payload"] def __init__(self, identifier, type=constants.FrameType.CAN_DATA, payload=b""): # type: (typing.Union[CanIdentifier, int], constants.FrameType, bytes) -> None if isinstance(identifier, int): self.identifier = CanIdentifier(identifier) else: self.identifier = identifier self.echo = False # Used only for Read self._type = type self.timestamp = 0 # Used only for Read self.payload = payload @classmethod def from_raw(cls, frame): """Convert from RawFrame. >>> raw = RawFrame(5, 0x20000001, constants.FrameType.CAN_DATA, _cconsts.NX_FRAME_FLAGS_TRANSMIT_ECHO, 0, b'') >>> CanFrame.from_raw(raw) CanFrame(CanIdentifier(0x1, extended=True), echo=True, timestamp=0x5) """ identifier = CanIdentifier.from_raw(frame.identifier) can_frame = CanFrame(identifier, constants.FrameType(frame.type), frame.payload) can_frame.timestamp = frame.timestamp can_frame.echo = bool(frame.flags & _cconsts.NX_FRAME_FLAGS_TRANSMIT_ECHO) return can_frame def to_raw(self): """Convert to RawFrame. >>> CanFrame(CanIdentifier(1, True), constants.FrameType.CAN_DATA).to_raw() RawFrame(timestamp=0x0, identifier=0x20000001, type=FrameType.CAN_DATA) >>> c = CanFrame(CanIdentifier(1, True), constants.FrameType.CAN_DATA) >>> c.echo = True >>> c.to_raw() RawFrame(timestamp=0x0, identifier=0x20000001, type=FrameType.CAN_DATA, flags=0x80) """ identifier = int(self.identifier) flags = 0 if self.echo: flags |= _cconsts.NX_FRAME_FLAGS_TRANSMIT_ECHO return RawFrame(self.timestamp, identifier, self.type, flags, 0, self.payload) @property def type(self): return self._type def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(CanFrame, other) return all(( self.identifier == other_frame.identifier, self.echo == other_frame.echo, self.type == other_frame.type, self.timestamp == other_frame.timestamp, self.payload == other_frame.payload)) else: return NotImplemented def __repr__(self): # type: () -> typing.Text """CanFrame debug representation. >>> CanFrame(1) CanFrame(CanIdentifier(0x1)) >>> CanFrame(1, constants.FrameType.CANFD_DATA, b'\x01') CanFrame(CanIdentifier(0x1), type=FrameType.CANFD_DATA, len(payload)=1) """ optional = [] if self.echo: optional.append('echo={}'.format(self.echo)) if self.type != constants.FrameType.CAN_DATA: optional.append('type={}'.format(self.type)) if self.timestamp != 0: optional.append('timestamp=0x{:x}'.format(self.timestamp)) if self.payload: optional.append('len(payload)={}'.format(len(self.payload))) if optional: optional_params = ', {}'.format(", ".join(optional)) else: optional_params = '' return "{}({}{})".format( type(self).__name__, self.identifier, optional_params) class CanBusErrorFrame(Frame): """Error detected on hardware bus of a :any:`nixnet.session.FrameInStreamSession`. .. note:: This requires enabling :any:`nixnet._session.intf.Interface.bus_err_to_in_strm`. See also :any:`nixnet.types.CanComm`. Attributes: timestamp(int): Absolute time when the bus error occurred. state (:any:`nixnet._enums.CanCommState`): Communication State tcvr_err (bool): Transceiver Error. bus_err (:any:`nixnet._enums.CanLastErr`): Last Error. tx_err_count (int): Transmit Error Counter. rx_err_count (int): Receive Error Counter. """ __slots__ = [ "timestamp", "state", "tcvr_err", "bus_err", "tx_err_count", "rx_err_count"] def __init__(self, timestamp, state, tcvr_err, bus_err, tx_err_count, rx_err_count): # type: (int, constants.CanCommState, bool, constants.CanLastErr, int, int) -> None self.timestamp = timestamp self.state = state self.tcvr_err = tcvr_err self.bus_err = bus_err self.tx_err_count = tx_err_count self.rx_err_count = rx_err_count @classmethod def from_raw(cls, frame): """Convert from RawFrame. >>> raw = RawFrame(0x64, 0x0, constants.FrameType.CAN_BUS_ERROR, 0, 0, b'\\x00\\x01\\x02\\x03\\x04') >>> CanBusErrorFrame.from_raw(raw) CanBusErrorFrame(0x64, CanCommState.ERROR_ACTIVE, True, CanLastErr.ACK, 1, 2) """ timestamp = frame.timestamp state = constants.CanCommState(six.indexbytes(frame.payload, 0)) tx_err_count = six.indexbytes(frame.payload, 1) rx_err_count = six.indexbytes(frame.payload, 2) bus_err = constants.CanLastErr(six.indexbytes(frame.payload, 3)) tcvr_err = six.indexbytes(frame.payload, 4) != 0 return CanBusErrorFrame(timestamp, state, tcvr_err, bus_err, tx_err_count, rx_err_count) def to_raw(self): """Convert to RawFrame. >>> CanBusErrorFrame(100, constants.CanCommState.BUS_OFF, True, constants.CanLastErr.STUFF, 1, 2).to_raw() RawFrame(timestamp=0x64, identifier=0x0, type=FrameType.CAN_BUS_ERROR, len(payload)=5) """ identifier = 0 flags = 0 info = 0 payload_data = [ self.state.value, self.tx_err_count, self.rx_err_count, self.bus_err.value, 1 if self.tcvr_err else 0, ] payload = bytes(bytearray(payload_data)) return RawFrame(self.timestamp, identifier, self.type, flags, info, payload) @property def type(self): return constants.FrameType.CAN_BUS_ERROR def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(CanBusErrorFrame, other) return all(( self.timestamp == other_frame.timestamp, self.state == other_frame.state, self.tcvr_err == other_frame.tcvr_err, self.bus_err == other_frame.bus_err, self.tx_err_count == other_frame.tx_err_count, self.rx_err_count == other_frame.rx_err_count)) else: return NotImplemented def __repr__(self): # type: () -> typing.Text """CanBusErrorFrame debug representation. >>> CanBusErrorFrame(100, constants.CanCommState.BUS_OFF, True, constants.CanLastErr.STUFF, 1, 2) CanBusErrorFrame(0x64, CanCommState.BUS_OFF, True, CanLastErr.STUFF, 1, 2) """ return "{}(0x{:x}, {}, {}, {}, {}, {})".format( type(self).__name__, self.timestamp, self.state, self.tcvr_err, self.bus_err, self.tx_err_count, self.rx_err_count) class LinFrame(object): """LIN Frame. Attributes: identifier(int): LIN frame arbitration identifier. echo(bool): If the frame is an echo of a successful transmit rather than being received from the network. type(:any:`nixnet._enums.FrameType`): Frame type. timestamp(int): Absolute time the XNET interface received the end-of-frame. eventslot(bool): Whether the frame was received within an event-triggered slot or an unconditional or sporadic slot. eventid(int): Identifier for an event-triggered slot. payload(bytes): A byte string representing the payload. """ __slots__ = [ "identifier", "echo", "type", "timestamp", "eventslot", "eventid", "payload"] _FRAME_ID_MASK = 0x0000003F def __init__(self, identifier, type=constants.FrameType.LIN_DATA, payload=b""): # type: (int, constants.FrameType, bytes) -> None self.identifier = identifier self.echo = False # Used only for Read self.type = type self.timestamp = 0 # Used only for Read self.eventslot = False # Used only for Read self.eventid = 0 # Used only for Read self.payload = payload @classmethod def from_raw(cls, frame): # type: (RawFrame) -> LinFrame """Convert from RawFrame. >>> raw = RawFrame(5, 2, constants.FrameType.LIN_DATA, 0x81, 1, b'\x01') >>> LinFrame.from_raw(raw) LinFrame(identifier=0x2, echo=True, timestamp=0x5, eventslot=True, eventid=1, len(payload)=1) >>> raw = RawFrame(5, 2, constants.FrameType.LIN_DATA, _cconsts.NX_FRAME_FLAGS_TRANSMIT_ECHO, 0, b'\x01') >>> LinFrame.from_raw(raw) LinFrame(identifier=0x2, echo=True, timestamp=0x5, len(payload)=1) """ identifier = frame.identifier & cls._FRAME_ID_MASK lin_frame = LinFrame(identifier, constants.FrameType(frame.type), frame.payload) lin_frame.timestamp = frame.timestamp lin_frame.echo = bool(frame.flags & _cconsts.NX_FRAME_FLAGS_TRANSMIT_ECHO) lin_frame.eventslot = bool(frame.flags & _cconsts.NX_FRAME_FLAGS_LIN_EVENT_SLOT) if lin_frame.eventslot: lin_frame.eventid = frame.info else: lin_frame.eventid = 0 return lin_frame def to_raw(self): # type: () -> RawFrame """Convert to RawFrame. >>> LinFrame(2, constants.FrameType.LIN_DATA).to_raw() RawFrame(timestamp=0x0, identifier=0x2, type=FrameType.LIN_DATA) >>> l = LinFrame(2, constants.FrameType.LIN_DATA) >>> l.echo = True >>> l.eventslot = True >>> l.eventid = 1 >>> l.to_raw() RawFrame(timestamp=0x0, identifier=0x2, type=FrameType.LIN_DATA, flags=0x81, info=0x1) """ if self.identifier != (self.identifier & self._FRAME_ID_MASK): _errors.check_for_error(_cconsts.NX_ERR_UNDEFINED_FRAME_ID) flags = 0 info = 0 if self.echo: flags |= _cconsts.NX_FRAME_FLAGS_TRANSMIT_ECHO if self.eventslot: flags |= _cconsts.NX_FRAME_FLAGS_LIN_EVENT_SLOT info |= self.eventid return RawFrame(self.timestamp, self.identifier, self.type, flags, info, self.payload) def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(LinFrame, other) return all(( self.identifier == other_frame.identifier, self.echo == other_frame.echo, self.type == other_frame.type, self.timestamp == other_frame.timestamp, self.eventslot == other_frame.eventslot, self.eventid == other_frame.eventid, self.payload == other_frame.payload)) else: return NotImplemented def __repr__(self): # type: () -> typing.Text """LinFrame debug representation. >>> LinFrame(2) LinFrame(identifier=0x2) >>> LinFrame(2, constants.FrameType.LIN_NO_RESPONSE, b'\x01') LinFrame(identifier=0x2, type=FrameType.LIN_NO_RESPONSE, len(payload)=1) """ optional = [] if self.echo: optional.append('echo={}'.format(self.echo)) if self.type != constants.FrameType.LIN_DATA: optional.append('type={}'.format(self.type)) if self.timestamp != 0: optional.append('timestamp=0x{:x}'.format(self.timestamp)) if self.eventslot: optional.append('eventslot={}'.format(self.eventslot)) if self.eventid != 0: optional.append('eventid={}'.format(self.eventid)) if self.payload: optional.append('len(payload)={}'.format(len(self.payload))) if optional: optional_params = ', {}'.format(", ".join(optional)) else: optional_params = '' return "{}(identifier=0x{:x}{})".format( type(self).__name__, self.identifier, optional_params) class LinBusErrorFrame(Frame): """Error detected on hardware bus of a :any:`nixnet.session.FrameInStreamSession`. .. note:: This requires enabling :any:`nixnet._session.intf.Interface.bus_err_to_in_strm`. See also :any:`nixnet.types.LinComm`. Attributes: timestamp(int): Absolute time when the bus error occurred. state (:any:`nixnet._enums.LinCommState`): Communication State. bus_err (:any:`nixnet._enums.LinLastErr`): Last Error. err_id (int): Identifier on bus. err_received (int): Received byte on bus err_expected (int): Expected byte on bus """ __slots__ = [ "timestamp", "state", "bus_err", "err_id", "err_received", "err_expected"] def __init__(self, timestamp, state, bus_err, err_id, err_received, err_expected): # type: (int, constants.LinCommState, constants.LinLastErr, int, int, int) -> None self.timestamp = timestamp self.state = state self.bus_err = bus_err self.err_id = err_id self.err_received = err_received self.err_expected = err_expected @classmethod def from_raw(cls, frame): """Convert from RawFrame. >>> raw = RawFrame(0x64, 0x0, constants.FrameType.LIN_BUS_ERROR, 0, 0, b'\\x00\\x01\\x02\\x03\\x04') >>> LinBusErrorFrame.from_raw(raw) LinBusErrorFrame(0x64, LinCommState.IDLE, LinLastErr.UNKNOWN_ID, 0x2, 3, 4) """ timestamp = frame.timestamp state = constants.LinCommState(six.indexbytes(frame.payload, 0)) bus_err = constants.LinLastErr(six.indexbytes(frame.payload, 1)) err_id = six.indexbytes(frame.payload, 2) err_received = six.indexbytes(frame.payload, 3) err_expected = six.indexbytes(frame.payload, 4) return LinBusErrorFrame(timestamp, state, bus_err, err_id, err_received, err_expected) def to_raw(self): """Convert to RawFrame. >>> LinBusErrorFrame(100, constants.LinCommState.INACTIVE, constants.LinLastErr.UNKNOWN_ID, 2, 3, 4).to_raw() RawFrame(timestamp=0x64, identifier=0x0, type=FrameType.LIN_BUS_ERROR, len(payload)=5) """ identifier = 0 flags = 0 info = 0 payload_data = [ self.state.value, self.bus_err.value, self.err_id, self.err_received, self.err_expected, ] payload = bytes(bytearray(payload_data)) return RawFrame(self.timestamp, identifier, self.type, flags, info, payload) @property def type(self): return constants.FrameType.LIN_BUS_ERROR def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(LinBusErrorFrame, other) return all(( self.timestamp == other_frame.timestamp, self.state == other_frame.state, self.bus_err == other_frame.bus_err, self.err_id == other_frame.err_id, self.err_received == other_frame.err_received, self.err_expected == other_frame.err_expected)) else: return NotImplemented def __repr__(self): # type: () -> typing.Text """LinBusErrorFrame debug representation. >>> LinBusErrorFrame(100, constants.LinCommState.INACTIVE, constants.LinLastErr.CRC, 1, 2, 3) LinBusErrorFrame(0x64, LinCommState.INACTIVE, LinLastErr.CRC, 0x1, 2, 3) """ return "{}(0x{:x}, {}, {}, 0x{:x}, {}, {})".format( type(self).__name__, self.timestamp, self.state, self.bus_err, self.err_id, self.err_received, self.err_expected) class DelayFrame(Frame): """Delay hardware when DelayFrame is outputted. .. note:: This requires :any:`nixnet._session.intf.Interface.out_strm_timng` to be in replay mode. Attributes: offset(int): Time to delay in milliseconds. """ __slots__ = [ "offset"] def __init__(self, offset): # type: (int) -> None self.offset = offset @classmethod def from_raw(cls, frame): """Convert from RawFrame. >>> raw = RawFrame(5, 0, constants.FrameType.SPECIAL_DELAY, 0, 0, b'') >>> DelayFrame.from_raw(raw) DelayFrame(5) """ return DelayFrame(frame.timestamp) def to_raw(self): """Convert to RawFrame. >>> DelayFrame(250).to_raw() RawFrame(timestamp=0xfa, identifier=0x0, type=FrameType.SPECIAL_DELAY) """ identifier = 0 flags = 0 info = 0 payload = b'' return RawFrame(self.offset, identifier, self.type, flags, info, payload) @property def type(self): return constants.FrameType.SPECIAL_DELAY def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(DelayFrame, other) return self.offset == other_frame.offset else: return NotImplemented def __repr__(self): # type: () -> typing.Text """DelayFrame debug representation. >>> DelayFrame(250) DelayFrame(250) """ return "{}({})".format(type(self).__name__, self.offset) class LogTriggerFrame(Frame): """Timestamp of when a trigger occurred. This frame is generated on input sessions when a rising edge is detected on an external connection. .. note:: This requires using :any:`nixnet._session.base.SessionBase.connect_terminals` to connect an external connection to the internal ``LogTrigger`` terminal. Attributes: timestamp(int): Absolute time that the trigger occurred. """ __slots__ = [ "timestamp"] def __init__(self, timestamp): # type: (int) -> None self.timestamp = timestamp @classmethod def from_raw(cls, frame): """Convert from RawFrame. >>> raw = RawFrame(5, 0, constants.FrameType.SPECIAL_LOG_TRIGGER, 0, 0, b'') >>> LogTriggerFrame.from_raw(raw) LogTriggerFrame(0x5) """ return LogTriggerFrame(frame.timestamp) def to_raw(self): """Convert to RawFrame. >>> LogTriggerFrame(250).to_raw() RawFrame(timestamp=0xfa, identifier=0x0, type=FrameType.SPECIAL_LOG_TRIGGER) """ identifier = 0 flags = 0 info = 0 payload = b'' return RawFrame(self.timestamp, identifier, self.type, flags, info, payload) @property def type(self): return constants.FrameType.SPECIAL_LOG_TRIGGER def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(LogTriggerFrame, other) return self.timestamp == other_frame.timestamp else: return NotImplemented def __repr__(self): # type: () -> typing.Text """LogTriggerFrame debug representation. >>> LogTriggerFrame(250) LogTriggerFrame(0xfa) """ return "{}(0x{:x})".format(type(self).__name__, self.timestamp) class StartTriggerFrame(Frame): """Timestamp of :any:`nixnet.session.FrameInStreamSession` start. .. note:: This requires enabling :any:`nixnet._session.intf.Interface.start_trig_to_in_strm`. Attributes: timestamp(int): Absolute time that the trigger occurred. """ __slots__ = [ "timestamp"] def __init__(self, timestamp): # type: (int) -> None self.timestamp = timestamp @classmethod def from_raw(cls, frame): """Convert from RawFrame. >>> raw = RawFrame(5, 0, constants.FrameType.SPECIAL_START_TRIGGER, 0, 0, b'') >>> StartTriggerFrame.from_raw(raw) StartTriggerFrame(0x5) """ return StartTriggerFrame(frame.timestamp) def to_raw(self): """Convert to RawFrame. >>> StartTriggerFrame(250).to_raw() RawFrame(timestamp=0xfa, identifier=0x0, type=FrameType.SPECIAL_START_TRIGGER) """ identifier = 0 flags = 0 info = 0 payload = b'' return RawFrame(self.timestamp, identifier, self.type, flags, info, payload) @property def type(self): return constants.FrameType.SPECIAL_START_TRIGGER def __eq__(self, other): if isinstance(other, self.__class__): other_frame = typing.cast(StartTriggerFrame, other) return self.timestamp == other_frame.timestamp else: return NotImplemented def __repr__(self): # type: () -> typing.Text """StartTriggerFrame debug representation. >>> StartTriggerFrame(250) StartTriggerFrame(0xfa) """ return "{}(0x{:x})".format(type(self).__name__, self.timestamp) class XnetFrame(FrameFactory): """Create `Frame` based on `RawFrame` content.""" __slots__ = () @classmethod def from_raw(cls, frame): """Convert from RawFrame.""" frame_type = { constants.FrameType.CAN_DATA: CanFrame, constants.FrameType.CAN20_DATA: CanFrame, constants.FrameType.CANFD_DATA: CanFrame, constants.FrameType.CANFDBRS_DATA: CanFrame, constants.FrameType.CAN_REMOTE: CanFrame, constants.FrameType.CAN_BUS_ERROR: CanBusErrorFrame, constants.FrameType.LIN_DATA: LinFrame, constants.FrameType.SPECIAL_DELAY: DelayFrame, constants.FrameType.SPECIAL_LOG_TRIGGER: LogTriggerFrame, constants.FrameType.SPECIAL_START_TRIGGER: StartTriggerFrame, }.get(frame.type) if frame_type is None: raise NotImplementedError("Unsupported frame type", frame.type) return frame_type.from_raw(frame)
mit
ce1e5013b10a465785a6e021fb39fce8
32.990421
118
0.591078
3.97959
false
false
false
false
ni/nixnet-python
tests/test_examples.py
1
5737
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import mock # type: ignore import pytest # type: ignore from nixnet import _cfuncs from nixnet import _ctypedefs from nixnet_examples import can_dynamic_database_creation from nixnet_examples import can_frame_queued_io from nixnet_examples import can_frame_stream_io from nixnet_examples import can_signal_conversion from nixnet_examples import can_signal_single_point_io from nixnet_examples import lin_dynamic_database_creation from nixnet_examples import lin_frame_stream_io from nixnet_examples import programmatic_database_usage MockXnetLibrary = mock.create_autospec(_cfuncs.XnetLibrary, spec_set=True, instance=True) MockXnetLibrary.nx_create_session.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_set_property.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_get_property.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_start.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_write_frame.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_read_frame.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_write_signal_single_point.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_read_signal_single_point.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_write_state.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_convert_frames_to_signals_single_point.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_convert_signals_to_frames_single_point.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_stop.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_clear.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_system_open.return_value = _ctypedefs.u32(0) MockXnetLibrary.nx_system_close.return_value = _ctypedefs.u32(0) MockXnetLibrary.nxdb_add_alias64.return_value = _ctypedefs.u32(0) MockXnetLibrary.nxdb_remove_alias.return_value = _ctypedefs.u32(0) MockXnetLibrary.nxdb_open_database.return_value = _ctypedefs.u32(0) MockXnetLibrary.nxdb_close_database.return_value = _ctypedefs.u32(0) MockXnetLibrary.nxdb_create_object.return_value = _ctypedefs.u32(0) MockXnetLibrary.nxdb_set_property.return_value = _ctypedefs.u32(0) def six_input(queue): # Leave `input_values` alone for easier debugging queue = copy.copy(queue) queue.reverse() def _six_input(prompt=""): value = queue.pop() return value return _six_input @pytest.mark.parametrize("input_values", [ ['y'], ['n'], ['invalid'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_can_dynamic_database_creation(input_values): with mock.patch('six.moves.input', six_input(input_values)): can_dynamic_database_creation.main() @pytest.mark.parametrize("input_values", [ ['y', '1, 2, 3', 'q'], ['n', '1, 2, 3', 'q'], ['invalid', '1, 2, 3', 'q'], ['y', 'invalid', 'q'], ['y', 'invalid'] + 0x100 * [''] + ['q'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_can_frame_queued_empty_session(input_values): with mock.patch('six.moves.input', six_input(input_values)): can_frame_queued_io.main() @pytest.mark.parametrize("input_values", [ ['y', '1, 2, 3', 'q'], ['n', '1, 2, 3', 'q'], ['invalid', '1, 2, 3', 'q'], ['y', 'invalid', 'q'], ['y', 'invalid'] + 0x100 * [''] + ['q'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_can_frame_stream_empty_session(input_values): with mock.patch('six.moves.input', six_input(input_values)): can_frame_stream_io.main() @pytest.mark.parametrize("input_values", [ ['y', '1, 2', 'q'], ['n', '1, 2', 'q'], ['invalid', '1, 2', 'q'], ['y', '1', 'q'], ['y', '1, 2, 3', 'q'], ['y', 'invalid', 'q'], ['y', 'invalid'] + 0x100 * [''] + ['q'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_can_signal_single_point_empty_session(input_values): with mock.patch('six.moves.input', six_input(input_values)): can_signal_single_point_io.main() @pytest.mark.parametrize("input_values", [ ['y'], ['n'], ['invalid'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_lin_dynamic_database_creation(input_values): with mock.patch('six.moves.input', six_input(input_values)): lin_dynamic_database_creation.main() @pytest.mark.parametrize("input_values", [ ['1, 2'], ['1'], ['<invalid>'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_can_signal_conversion_empty_session(input_values): with mock.patch('six.moves.input', six_input(input_values)): can_signal_conversion.main() @pytest.mark.parametrize("input_values", [ ['y', '1, 2, 3', 'q'], ['n', '1, 2, 3', 'q'], ['invalid', '1, 2, 3', 'q'], ['y', 'invalid', 'q'], ['y', 'invalid'] + 0x100 * [''] + ['q'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_lin_frame_stream_empty_session(input_values): with mock.patch('six.moves.input', six_input(input_values)): lin_frame_stream_io.main() @pytest.mark.parametrize("input_values", [ ['y', '1, 2'], ['n', '1, 2'], ['y', 'invalid'], ['invalid', 'invalid'], ]) @mock.patch('nixnet._cfuncs.lib', MockXnetLibrary) @mock.patch('time.sleep', lambda time: None) def test_programmatic_database_usage(input_values): with mock.patch('six.moves.input', six_input(input_values)): programmatic_database_usage.main()
mit
55669814855548ecd50a90e9396b2dda
34.196319
90
0.677009
2.907755
false
true
false
false
ni/nixnet-python
tests/conftest.py
2
1910
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import pytest # type: ignore def pytest_addoption(parser): parser.addoption( "--can-out-interface", default="None", action="store", help="The CAN interface to use with the tests") parser.addoption( "--can-in-interface", default="None", action="store", help="The CAN interface to use with the tests") parser.addoption( "--lin-out-interface", default="None", action="store", help="The LIN interface to use with the tests") parser.addoption( "--lin-in-interface", default="None", action="store", help="The LIN interface to use with the tests") @pytest.fixture def can_in_interface(request): interface = request.config.getoption("--can-in-interface") if interface.lower() == "none": pytest.skip("Test requires a CAN board") return interface @pytest.fixture def can_out_interface(request): interface = request.config.getoption("--can-out-interface") if interface.lower() == "none": pytest.skip("Test requires a CAN board") return interface @pytest.fixture def lin_in_interface(request): interface = request.config.getoption("--lin-in-interface") if interface.lower() == "none": pytest.skip("Test requires a LIN board") return interface @pytest.fixture def lin_out_interface(request): interface = request.config.getoption("--lin-out-interface") if interface.lower() == "none": pytest.skip("Test requires a LIN board") return interface @pytest.fixture def custom_database_path(): tests_path = os.path.dirname(__file__) root_path = os.path.dirname(tests_path) database_path = os.path.join(root_path, 'nixnet_examples', 'databases', 'custom_database.dbc') return database_path
mit
de668ebdda1d281df30a7b0c632f1a38
27.939394
98
0.660209
3.858586
false
true
false
false
ni/nixnet-python
nixnet/database/_find_object.py
1
1674
from __future__ import absolute_import from __future__ import division from __future__ import print_function import typing # NOQA: F401 from nixnet import _cconsts from nixnet import _errors from nixnet import _funcs from nixnet import constants from nixnet.database import _database_object # NOQA: F401 def find_object( parent_handle, # type: int object_class, # type: typing.Any object_name, # type: typing.Text ): # type: (...) -> _database_object.DatabaseObject from nixnet.database._cluster import Cluster from nixnet.database._ecu import Ecu from nixnet.database._frame import Frame from nixnet.database._lin_sched import LinSched from nixnet.database._lin_sched_entry import LinSchedEntry from nixnet.database._pdu import Pdu from nixnet.database._signal import Signal from nixnet.database._subframe import SubFrame class_enum = { Cluster: constants.ObjectClass.CLUSTER, Ecu: constants.ObjectClass.ECU, Frame: constants.ObjectClass.FRAME, LinSched: constants.ObjectClass.LIN_SCHED, LinSchedEntry: constants.ObjectClass.LIN_SCHED_ENTRY, Pdu: constants.ObjectClass.PDU, Signal: constants.ObjectClass.SIGNAL, SubFrame: constants.ObjectClass.SUBFRAME, }.get(object_class) if class_enum is None: raise ValueError("Unsupported value provided for argument object_class.", object_class) found_handle = _funcs.nxdb_find_object(parent_handle, class_enum, object_name) if found_handle == 0: _errors.raise_xnet_error(_cconsts.NX_ERR_DATABASE_OBJECT_NOT_FOUND) return object_class(_handle=found_handle)
mit
693e515833e35b0ced1b358aea95e738
34.617021
95
0.71147
3.821918
false
false
false
false
ni/nixnet-python
nixnet/_session/base.py
1
31408
from __future__ import absolute_import from __future__ import division from __future__ import print_function import ctypes # type: ignore import typing # NOQA: F401 import warnings from nixnet import _ctypedefs from nixnet import _errors from nixnet import _funcs from nixnet import _props from nixnet import _utils from nixnet import constants from nixnet import errors from nixnet import types # NOQA: F401 from nixnet._session import intf as session_intf from nixnet._session import j1939 as session_j1939 class SessionBase(object): """Session base object.""" def __init__( self, database_name, # type: typing.Text cluster_name, # type: typing.Text list, # type: typing.Text interface_name, # type: typing.Text mode, # type: constants.CreateSessionMode ): # type: (...) -> None """Create an XNET session at run time using named references to database objects. This function creates a session using the named database objects specified in 'list' from the database named in 'database_name'. This function is intended to be used by session classes that derive from SessionBase; therefore, it is not public. Args: database_name: A string representing the XNET database to use for interface configuration. The database name must use the <alias> or <filepath> syntax (refer to Databases). cluster_name: A string representing the XNET cluster to use for interface configuration. The name must specify a cluster from the database given in the database_name parameter. If it is left blank, the cluster is extracted from the list parameter; this is not allowed for modes of 'constants.CreateSessionMode.FRAME_IN_STREAM' or 'constants.CreateSessionMode.FRAME_OUT_STREAM'. list: A list of strings describing signals or frames for the session. The list syntax depends on the mode. Refer to mode spefic session classes defined below for 'list' syntax. interface_name: A string representing the XNET Interface to use for this session. If Mode is 'constants.CreateSessionMode.SIGNAL_CONVERSION_SINGLE_POINT', this input is ignored. You can set it to an empty string. mode: The session mode. See :any:`nixnet._enums.CreateSessionMode`. Returns: A session base object. """ self._handle = None # To satisfy `__del__` in case nx_create_session throws self._handle = _funcs.nx_create_session(database_name, cluster_name, list, interface_name, mode) self._intf = session_intf.Interface(self._handle) self._j1939 = session_j1939.J1939(self._handle) def __del__(self): if self._handle is not None: warnings.warn( 'Session was not explicitly closed before it was destructed. ' 'Resources on the device may still be reserved.', errors.XnetResourceWarning) def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): self.close() def __eq__(self, other): if isinstance(other, self.__class__): return self._handle == typing.cast(SessionBase, other)._handle else: return NotImplemented def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result else: return not result def __hash__(self): return hash(self._handle) def __repr__(self): # type: () -> typing.Text return '{}(handle={})'.format(type(self).__name__, self._handle) def close(self): # type: () -> None """Close (clear) the XNET session. This function stops communication for the session and releases all resources the session uses. It internally calls :any:`nixnet._session.base.SessionBase.stop` with normal scope, so if this is the last session using the interface, communication stops. You typically use 'close' when you need to close the existing session to create a new session that uses the same objects. For example, if you create a session for a frame named frame_a using Frame Output Single-Point mode, then you create a second session for frame_a using Frame Output Queued mode, the second call to the session constructor returns an error, because frame_a can be accessed using only one output mode. If you call 'close' before the second constructor call, you can close the previous use of frame_a to create the new session. """ if self._handle is None: warnings.warn( 'Attempting to close NI-XNET session but session was already ' 'closed', errors.XnetResourceWarning) return _funcs.nx_clear(self._handle) self._handle = None def start(self, scope=constants.StartStopScope.NORMAL): # type: (constants.StartStopScope) -> None """Start communication for the XNET session. Because the session is started automatically by default, this function is optional. This function is for more advanced applications to start multiple sessions in a specific order. For more information about the automatic start feature, refer to the :any:`nixnet._session.base.SessionBase.auto_start` property. For each physical interface, the NI-XNET hardware is divided into two logical units: Sessions: You can create one or more sessions, each of which contains frames or signals to be transmitted (or received) on the bus. Interface: The interface physically connects to the bus and transmits (or receives) data for the sessions. You can start each logical unit separately. When a session is started, all contained frames or signals are placed in a state where they are ready to communicate. When the interface is started, it takes data from all started sessions to communicate with other nodes on the bus. For a specification of the state models for the session and interface, refer to State Models. If an output session starts before you write data, or you read an input session before it receives a frame, default data is used. For more information, refer to the XNET Frame Default Payload and XNET Signal Default Value properties. Args: scope(:any:`nixnet._enums.StartStopScope`): Describes the impact of this operation on the underlying state models for the session and its interface. """ _funcs.nx_start(self._handle, scope) def stop(self, scope=constants.StartStopScope.NORMAL): # type: (constants.StartStopScope) -> None """Stop communication for the XNET session. Because the session is stopped automatically when closed (cleared), this function is optional. For each physical interface, the NI-XNET hardware is divided into two logical units: Sessions: You can create one or more sessions, each of which contains frames or signals to be transmitted (or received) on the bus. Interface: The interface physically connects to the bus and transmits (or receives) data for the sessions. You can stop each logical unit separately. When a session is stopped, all contained frames or signals are placed in a state where they are no longer ready to communicate. When the interface is stopped, it no longer takes data from sessions to communicate with other nodes on the bus. For a specification of the state models for the session and interface, refer to State Models. Args: scope(:any:`nixnet._enums.StartStopScope`): Describes the impact of this operation on the underlying state models for the session and its interface. """ _funcs.nx_stop(self._handle, scope) def flush(self): # type: () -> None """Flushes (empties) all XNET session queues. With the exception of single-point modes, all sessions use queues to store frames. For input modes, the queues store frame values (or corresponding signal values) that have been received, but not obtained by calling the read function. For output sessions, the queues store frame values provided to write function, but not transmitted successfully. :any:`nixnet._session.base.SessionBase.start` and :any:`nixnet._session.base.SessionBase.stop` have no effect on these queues. Use 'flush' to discard all values in the session's queues. For example, if you call a write function to write three frames, then immediately call :any:`nixnet._session.base.SessionBase.stop`, then call :any:`nixnet._session.base.SessionBase.start` a few seconds later, the three frames transmit. If you call 'flush' between :any:`nixnet._session.base.SessionBase.stop` and :any:`nixnet._session.base.SessionBase.start`, no frames transmit. As another example, if you receive three frames, then call :any:`nixnet._session.base.SessionBase.stop`, the three frames remains in the queue. If you call :any:`nixnet._session.base.SessionBase.start` a few seconds later, then call a read function, you obtain the three frames received earlier, potentially followed by other frames received after calling :any:`nixnet._session.base.SessionBase.start`. If you call 'flush' between :any:`nixnet._session.base.SessionBase.stop` and :any:`nixnet._session.base.SessionBase.start`, read function returns only frames received after the calling :any:`nixnet._session.base.SessionBase.start`. """ _funcs.nx_flush(self._handle) def wait_for_transmit_complete(self, timeout=10): # type: (float) -> None """Wait for transmition to complete. All frames written for the session have been transmitted on the bus. This condition applies to CAN, LIN, and FlexRay. This condition is state based, and the state is Boolean (true/false). Args: timeout(float): The maximum amount of time to wait in seconds. """ _funcs.nx_wait(self._handle, constants.Condition.TRANSMIT_COMPLETE, 0, timeout) def wait_for_intf_communicating(self, timeout=10): # type: (float) -> None """Wait for the interface to begin communication on the network. If a start trigger is configured for the interface, this first waits for the trigger. Once the interface is started, this waits for the protocol's communication state to transition to a value that indicates communication with remote nodes. After this wait succeeds, calls to 'read_state' will return: :any:`nixnet._enums.CanCommState`: 'constants.CAN_COMM.ERROR_ACTIVE' :any:`nixnet._enums.CanCommState`: 'constants.CAN_COMM.ERROR_PASSIVE' 'constants.ReadState.TIME_COMMUNICATING': Valid time for communication (invalid time of 0 prior) Args: timeout(float): The maximum amount of time to wait in seconds. """ _funcs.nx_wait(self._handle, constants.Condition.INTF_COMMUNICATING, 0, timeout) def wait_for_intf_remote_wakeup(self, timeout=10): # type: (float) -> None """Wait for interface remote wakeup. Wait for the interface to wakeup due to activity by a remote node on the network. This wait is used for CAN, when you set the 'can_tcvr_state' property to 'constants.CanTcvrState.SLEEP'. Although the interface itself is ready to communicate, this places the transceiver into a sleep state. When a remote CAN node transmits a frame, the transceiver wakes up, and communication is restored. This wait detects that remote wakeup. This wait is used for LIN when you set 'lin_sleep' property to 'constants.LinSleep.REMOTE_SLEEP' or 'constants.LinSleep.LOCAL_SLEEP'. When asleep, if a remote LIN ECU transmits the wakeup pattern (break), the XNET LIN interface detects this transmission and wakes up. This wait detects that remote wakeup. Args: timeout(float): The maximum amount of time to wait in seconds. """ _funcs.nx_wait(self._handle, constants.Condition.INTF_REMOTE_WAKEUP, 0, timeout) def connect_terminals(self, source, destination): # type: (typing.Text, typing.Text) -> None """Connect terminals on the XNET interface. This function connects a source terminal to a destination terminal on the interface hardware. The XNET terminal represents an external or internal hardware connection point on a National Instruments XNET hardware product. External terminals include PXI Trigger lines for a PXI card, RTSI terminals for a PCI card, or the single external terminal for a C Series module. Internal terminals include timebases (clocks) and logical entities such as a start trigger. The terminal inputs use the Terminal I/O names. Typically, one of the pair is an internal and the other an external. Args: source(str): Connection source name. destination(str): Connection destination name. """ _funcs.nx_connect_terminals(self._handle, source, destination) def disconnect_terminals(self, source, destination): # type: (typing.Text, typing.Text) -> None """Disconnect terminals on the XNET interface. This function disconnects a specific pair of source/destination terminals previously connected with :any:`nixnet._session.base.SessionBase.connect_terminals`. When the final session for a given interface is cleared, NI-XNET automatically disconnects all terminal connections for that interface. Therefore, 'disconnect_terminals' is not required for most applications. This function typically is used to change terminal connections dynamically while an application is running. To disconnect a terminal, you first must stop the interface using :any:`nixnet._session.base.SessionBase.stop` with the Interface Only scope. Then you can call 'disconnect_terminals' and :any:`nixnet._session.base.SessionBase.connect_terminals` to adjust terminal connections. Finally, you can call :any:`nixnet._session.base.SessionBase.start` with the Interface Only scope to restart the interface. You can disconnect only a terminal that has been previously connected. Attempting to disconnect a nonconnected terminal results in an error. Args: source(str): Connection source name. destination(str): Connection destination name. """ _funcs.nx_disconnect_terminals(self._handle, source, destination) def change_lin_schedule(self, sched_index): # type: (int) -> None """Writes communication states of an XNET session. This function writes a request for the LIN interface to change the running schedule. According to the LIN protocol, only the master executes schedules, not slaves. If the :any:`nixnet._session.intf.Interface.lin_master` property is false (slave), this write function implicitly sets that property to true (master). If the interface currently is running as a slave, this write returns an error, because it cannot change to master while running. Args: sched_index(int): Index to the schedule table that the LIN master executes. The schedule tables are sorted the way they are returned from the database with the `nixnet.database._cluster.Cluster.lin_schedules` property. """ _funcs.nx_write_state(self._handle, constants.WriteState.LIN_SCHEDULE_CHANGE, _ctypedefs.u32(sched_index)) def change_lin_diagnostic_schedule(self, schedule): # type: (constants.LinDiagnosticSchedule) -> None """Writes communication states of an XNET session. This function writes a request for the LIN interface to change the diagnostic schedule. Args: schedule(:any:`nixnet._enums.LinDiagnosticSchedule`): Diagnostic schedule that the LIN master executes. """ _funcs.nx_write_state(self._handle, constants.WriteState.LIN_DIAGNOSTIC_SCHEDULE_CHANGE, _ctypedefs.u32(schedule.value)) # NOQA: E501 @property def time_current(self): # type: () -> int """int: Current interface time.""" state_value_ctypes = _ctypedefs.nxTimestamp_t() state_size = ctypes.sizeof(state_value_ctypes) _funcs.nx_read_state( self._handle, constants.ReadState.TIME_CURRENT, state_size, ctypes.pointer(state_value_ctypes)) time = state_value_ctypes.value return time @property def time_start(self): # type: () -> int """int: Time the interface was started.""" state_value_ctypes = _ctypedefs.nxTimestamp_t() state_size = ctypes.sizeof(state_value_ctypes) _funcs.nx_read_state( self._handle, constants.ReadState.TIME_START, state_size, ctypes.pointer(state_value_ctypes)) time = state_value_ctypes.value if time == 0: # The interface is not communicating. _errors.check_for_error(constants.Err.SESSION_NOT_STARTED.value) return time @property def time_communicating(self): # type: () -> int """int: Time the interface started communicating. The time is usually later than ``time_start`` because the interface must undergo a communication startup procedure. """ state_value_ctypes = _ctypedefs.nxTimestamp_t() state_size = ctypes.sizeof(state_value_ctypes) _funcs.nx_read_state( self._handle, constants.ReadState.TIME_COMMUNICATING, state_size, ctypes.pointer(state_value_ctypes)) time = state_value_ctypes.value if time == 0: # The interface is not communicating. _errors.check_for_error(constants.Err.SESSION_NOT_STARTED.value) return time @property def state(self): # type: () -> constants.SessionInfoState """:any:`nixnet._enums.SessionInfoState`: Session running state.""" state_value_ctypes = _ctypedefs.u32() state_size = ctypes.sizeof(state_value_ctypes) _funcs.nx_read_state( self._handle, constants.ReadState.SESSION_INFO, state_size, ctypes.pointer(state_value_ctypes)) state = state_value_ctypes.value return constants.SessionInfoState(state) @property def can_comm(self): # type: () -> types.CanComm """:any:`nixnet.types.CanComm`: CAN Communication state""" state_value_ctypes = _ctypedefs.u32() state_size = ctypes.sizeof(state_value_ctypes) _funcs.nx_read_state( self._handle, constants.ReadState.CAN_COMM, state_size, ctypes.pointer(state_value_ctypes)) bitfield = state_value_ctypes.value return _utils.parse_can_comm_bitfield(bitfield) @property def lin_comm(self): # type: () -> types.LinComm """:any:`nixnet.types.LinComm`: LIN Communication state""" state_value_ctypes = (_ctypedefs.u32 * 2)() # type: ignore state_size = ctypes.sizeof(state_value_ctypes) _funcs.nx_read_state( self._handle, constants.ReadState.LIN_COMM, state_size, ctypes.pointer(state_value_ctypes)) first = state_value_ctypes[0].value second = state_value_ctypes[1].value return _utils.parse_lin_comm_bitfield(first, second) def check_fault(self): # type: () -> None """Check for an asynchronous fault. A fault is an error that occurs asynchronously to the NI-XNET application calls. The fault cause may be related to network communication, but it also can be related to XNET hardware, such as a fault in the onboard processor. Although faults are extremely rare, nxReadState provides a detection method distinct from the status of NI-XNET function calls, yet easy to use alongside the common practice of checking the communication state. """ state_value_ctypes = _ctypedefs.u32() state_size = ctypes.sizeof(state_value_ctypes) fault = _funcs.nx_read_state( self._handle, constants.ReadState.SESSION_INFO, state_size, ctypes.pointer(state_value_ctypes)) _errors.check_for_error(fault) @property def intf(self): # type: () -> session_intf.Interface """:any:`nixnet._session.intf.Interface`: Returns the Interface configuration object for the session.""" return self._intf @property def j1939(self): # type: () -> session_j1939.J1939 """:any:`nixnet._session.j1939.J1939`: Returns the J1939 configuration object for the session.""" return self._j1939 @property def application_protocol(self): # type: () -> constants.AppProtocol """:any:`nixnet._enums.AppProtocol`: This property returns the application protocol that the session uses. The database used with the session determines the application protocol. """ return constants.AppProtocol(_props.get_session_application_protocol(self._handle)) @property def auto_start(self): # type: () -> bool """bool: Automatically starts the output session on the first call to the appropriate write function. For input sessions, start always is performed within the first call to the appropriate read function (if not already started using :any:`nixnet._session.base.SessionBase.start`). This is done because there is no known use case for reading a stopped input session. For output sessions, as long as the first call to the appropriate write function contains valid data, you can leave this property at its default value of true. If you need to call the appropriate write function multiple times prior to starting the session, or if you are starting multiple sessions simultaneously, you can set this property to false. After calling the appropriate write function as desired, you can call :any:`nixnet._session.base.SessionBase.start` to start the session(s). When automatic start is performed, it is equivalent to :any:`nixnet._session.base.SessionBase.start` with scope set to Normal. This starts the session itself, and if the interface is not already started, it starts the interface also. """ return _props.get_session_auto_start(self._handle) @auto_start.setter def auto_start(self, value): # type: (bool) -> None _props.set_session_auto_start(self._handle, value) @property def cluster_name(self): # type: () -> typing.Text """str: This property returns the cluster (network) name used with the session.""" return _props.get_session_cluster_name(self._handle) @property def database_name(self): # type: () -> typing.Text """str: This property returns the database name used with the session.""" return _props.get_session_database_name(self._handle) @property def mode(self): # type: () -> constants.CreateSessionMode """:any:`nixnet._enums.CreateSessionMode`: This property returns the mode associated with the session. For more information, refer to :any:`nixnet._enums.CreateSessionMode`. """ return constants.CreateSessionMode(_props.get_session_mode(self._handle)) @property def num_pend(self): # type: () -> int """int: This property returns the number of values (frames or signals) pending for the session. For input sessions, this is the number of frame/signal values available to the appropriate read function. If you call the appropriate read function with number to read of this number and timeout of 0.0, the appropriate read function should return this number of values successfully. For output sessions, this is the number of frames/signal values provided to the appropriate write function but not yet transmitted onto the network. Stream frame sessions using FlexRay or CAN FD protocol may use a variable size of frames. In these cases, this property assumes the largest possible frame size. If you use smaller frames, the real number of pending values might be higher. The largest possible frames sizes are: CAN FD: 64 byte payload. FlexRay: The higher value of the frame size in the static segment and the maximum frame size in the dynamic segment. The XNET Cluster FlexRay Payload Length Maximum property provides this value. """ return _props.get_session_num_pend(self._handle) @property def num_unused(self): # type: () -> int """int: This property returns the number of values (frames or signals) unused for the session. If you get this property prior to starting the session, it provides the size of the underlying queue(s). Contrary to the Queue Size property, this value is in number of frames for Frame I/O, not number of bytes; for Signal I/O, it is the number of signal values in both cases. After start, this property returns the queue size minus the :any:`Number of Values Pending <nixnet._session.base.SessionBase.num_pend>` property. For input sessions, this is the number of frame/signal values unused in the underlying queue(s). For output sessions, this is the number of frame/signal values you can provide to a subsequent call to the appropriate write function. If you call the appropriate write function with this number of values and timeout of 0.0, it should return success. Stream frame sessions using FlexRay or CAN FD protocol may use a variable size of frames. In these cases, this property assumes the largest possible frame size. If you use smaller frames, the real number of pending values might be higher. The largest possible frames sizes are: CAN FD: 64 byte payload. FlexRay: The higher value of the frame size in the static segment and the maximum frame size in the dynamic segment. The XNET Cluster FlexRay Payload Length Maximum property provides this value. """ return _props.get_session_num_unused(self._handle) @property def protocol(self): # type: () -> constants.Protocol """:any:`nixnet._enums.Protocol`: This property returns the protocol that the interface in the session uses.""" return constants.Protocol(_props.get_session_protocol(self._handle)) @property def queue_size(self): # type: () -> int """int: Get or set queue size. For output sessions, queues store data passed to the appropriate write function and not yet transmitted onto the network. For input sessions, queues store data received from the network and not yet obtained using the appropriate read function. For most applications, the default queue sizes are sufficient. You can write to this property to override the default. When you write (set) this property, you must do so prior to the first session start. You cannot set this property again after calling :any:`nixnet._session.base.SessionBase.stop`. For signal I/O sessions, this property is the number of signal values stored. This is analogous to the number of values you use with the appropriate read or write function. For frame I/O sessions, this property is the number of bytes of frame data stored. For standard CAN or LIN frame I/O sessions, each frame uses exactly 24 bytes. You can use this number to convert the Queue Size (in bytes) to/from the number of frame values. For CAN FD and FlexRay frame I/O sessions, each frame value size can vary depending on the payload length. For more information, refer to Raw Frame Format. For Signal I/O XY sessions, you can use signals from more than one frame. Within the implementation, each frame uses a dedicated queue. According to the formulas below, the default queue sizes can be different for each frame. If you read the default Queue Size property for a Signal Input XY session, the largest queue size is returned, so that a call to the appropriate read function of that size can empty all queues. If you read the default Queue Size property for a Signal Output XY session, the smallest queue size is returned, so that a call to the appropriate write function of that size can succeed when all queues are empty. If you write the Queue Size property for a Signal I/O XY session, that size is used for all frames, so you must ensure that it is sufficient for the frame with the fastest transmit time. For Signal I/O Waveform sessions, you can use signals from more than one frame. Within the implementation, each frame uses a dedicated queue. The Queue Size property does not represent the memory in these queues, but rather the amount of time stored. The default queue allocations store Application Time worth of resampled signal values. If you read the default Queue Size property for a Signal I/O Waveform session, it returns Application Time multiplied by the time Resample Rate. If you write the Queue Size property for a Signal I/O Waveform session, that value is translated from a number of samples to a time, and that time is used to allocate memory for each queue. For Single-Point sessions (signal or frame), this property is ignored. Single-Point sessions always use a value of 1 as the effective queue size. """ return _props.get_session_queue_size(self._handle) @queue_size.setter def queue_size(self, value): # type: (int) -> None _props.set_session_queue_size(self._handle, value)
mit
1f3a3b0089305f437f060078421ea4af
44.126437
142
0.661042
4.531525
false
false
false
false
ni/nixnet-python
nixnet/database/_signal.py
1
20178
from __future__ import absolute_import from __future__ import division from __future__ import print_function import typing # NOQA: F401 from nixnet import _cconsts from nixnet import _errors from nixnet import _props from nixnet import constants from nixnet.database import _database_object from nixnet.database import _dbc_attributes from nixnet.database import _dbc_signal_value_table # workaround to avoid circular imports caused by mypy type annotations MYPY = False if MYPY: from nixnet.database import _frame # NOQA: F401 from nixnet.database import _pdu # NOQA: F401 from nixnet.database import _subframe # NOQA: F401 class Signal(_database_object.DatabaseObject): """Database signal""" def __init__( self, **kwargs # type: int ): # type: (...) -> None if not kwargs or '_handle' not in kwargs: raise TypeError() self._handle = kwargs['_handle'] self._dbc_attributes = None # type: typing.Optional[_dbc_attributes.DbcAttributeCollection] self._dbc_signal_value_table = _dbc_signal_value_table.DbcSignalValueTable(self._handle) def __eq__(self, other): if isinstance(other, self.__class__): return self._handle == other._handle else: return NotImplemented def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result else: return not result def __hash__(self): return hash(self._handle) def __repr__(self): return '{}(handle={})'.format(type(self).__name__, self._handle) def check_config_status(self): # type: () -> None """Check this signal's configuration status. By default, incorrectly configured signals in the database are not returned from :any:`Frame.sigs` because they cannot be used in the bus communication. You can change this behavior by setting :any:`Database.show_invalid_from_open` to `True`. When a signal configuration status becomes invalid after the database is opened, the signal still is returned from :any:`Frame.sigs` even if :any:`Database.show_invalid_from_open` is `False`. Examples of invalid signal configuration: * The signal is specified using bits outside the frame payload. * The signal overlaps another signal in the frame. For example, two multiplexed signals with the same multiplexer value are using the same bit in the frame payload. * The signal with integer data type (signed or unsigned) is specified with more than 52 bits. This is not allowed due to internal limitation of the double data type that NI-XNET uses for signal values. * The frame containing the signal is invalid (for example, a CAN frame is defined with more than 8 payload bytes). Raises: :any:`XnetError`: The signal is incorrectly configured. """ status_code = _props.get_signal_config_status(self._handle) _errors.check_for_error(status_code) @property def byte_ordr(self): # type: () -> constants.SigByteOrdr """:any:`SigByteOrdr`: Signal byte order in the frame payload. This property defines how signal bytes are ordered in the frame payload when the frame is loaded in memory. This property is required. If the property does not contain a valid value, and you create an XNET session that uses this signal, the session returns an error. To ensure that the property contains a valid value, you can do one of the following: * Use a database file (or alias) to create the session. The file formats require a valid value in the text for this property. * Set a value using the nxdbSetProperty function. This is needed when you create your own in-memory database (*:memory:*) rather than use a file. The property does not contain a default in this case, so you must set a valid value prior to creating a session. """ return constants.SigByteOrdr(_props.get_signal_byte_ordr(self._handle)) @byte_ordr.setter def byte_ordr(self, value): # type: (constants.SigByteOrdr) -> None _props.set_signal_byte_ordr(self._handle, value.value) @property def comment(self): # type: () -> typing.Text """str: Get or set a comment describing the signal object. A comment is a string containing up to 65535 characters. """ return _props.get_signal_comment(self._handle) @comment.setter def comment(self, value): # type: (typing.Text) -> None _props.set_signal_comment(self._handle, value) @property def data_type(self): # type: () -> constants.SigDataType """:any:`SigDataType`: Get or set the signal data type. This property determines how the bits of a signal in a frame must be interpreted to build a value. This property is required. If the property does not contain a valid value, and you create an XNET session that uses this signal, the session returns an error. To ensure that the property contains a valid value, you can do one of the following: * Use a database file (or alias) to create the session. The file formats require a valid value in the text for this property. * Set a value at runtime using this property. This is needed when you create your own in-memory database (*:memory:*) rather than use a file. The property does not contain a default in this case, so you must set a valid value prior to creating a session. """ return constants.SigDataType(_props.get_signal_data_type(self._handle)) @data_type.setter def data_type(self, value): # type: (constants.SigDataType) -> None _props.set_signal_data_type(self._handle, value.value) @property def dbc_attributes(self): # type: () -> _dbc_attributes.DbcAttributeCollection """:any:`DbcAttributeCollection`: Access the signal's DBC attributes.""" if self._dbc_attributes is None: self._dbc_attributes = _dbc_attributes.DbcAttributeCollection(self._handle) return self._dbc_attributes @property def dbc_signal_value_table(self): # type: () -> _dbc_signal_value_table.DbcSignalValueTable """:any:`DbcSignalValueTable`: Access the signal's DBC value table.""" return self._dbc_signal_value_table @property def default(self): # type: () -> float """float: Get or set the signal default value, specified as scaled floating-point units. The initial value of this property comes from the database. If the database does not provide a value, this property uses a default value of 0.0. For all three signal output sessions, this property is used when a frame transmits prior to writing to a session. The :any:`Frame.default_payload` property is used as the initial payload, then the default value of each signal is mapped into that payload using this property, and the result is used for the frame transmit. For all three signal input sessions, this property is returned for each signal when reading a session prior to receiving the first frame. For more information about when this property is used, refer to the discussion of read and write for each session mode. """ return _props.get_signal_default(self._handle) @default.setter def default(self, value): # type: (float) -> None _props.set_signal_default(self._handle, value) @property def frame(self): # type: () -> _frame.Frame """:any:`Frame<_frame.Frame>`: Returns the signal parent frame object. The parent frame is defined when the signal object is created. You cannot change it afterwards. """ from nixnet.database import _frame # NOQA: F811 ref = _props.get_signal_frame_ref(self._handle) return _frame.Frame(_handle=ref) @property def max(self): # type: () -> float """float: Get or set the scaled signal value maximum. Session read and write methods do not limit the signal value to a maximum value. Use this database property to set the maximum value. """ return _props.get_signal_max(self._handle) @max.setter def max(self, value): # type: (float) -> None _props.set_signal_max(self._handle, value) @property def min(self): # type: () -> float """float: The scaled signal value minimum. Session read and write methods do not limit the signal value to a minimum value. Use this database property to set the minimum value. """ return _props.get_signal_min(self._handle) @min.setter def min(self, value): # type: (float) -> None _props.set_signal_min(self._handle, value) @property def name(self): # type: () -> typing.Text """str: Get or set a string identifying a signal object. Lowercase letters, uppercase letters, numbers, and the underscore (_) are valid characters for the short name. The space ( ), period (.), and other special characters are not supported within the name. The short name must begin with a letter (uppercase or lowercase) or underscore, and not a number. The short name is limited to 128 characters. A signal name must be unique for all signals in a frame. This short name does not include qualifiers to ensure that it is unique, such as the database, cluster, and frame name. It is for display purposes. """ return _props.get_signal_name(self._handle) @name.setter def name(self, value): # type: (typing.Text) -> None _props.set_signal_name(self._handle, value) @property def name_unique_to_cluster(self): # type: () -> typing.Text """str: Returns a signal name unique to the cluster that contains the signal. If the single name is not unique within the cluster, the name is <frame-name>.<signal-name>. You can pass the name to the `find` function to retrieve the reference to the object, while the single name is not guaranteed success in `find` because it may be not unique in the cluster. """ return _props.get_signal_name_unique_to_cluster(self._handle) @property def num_bits(self): # type: () -> int """int: The number of bits the signal uses in the frame payload. IEEE Float numbers are limited to 32 bit or 64 bit. Integer (signed and unsigned) numbers are limited to 1-52 bits. NI-XNET converts all integers to doubles (64-bit IEEE Float). Integer numbers with more than 52 bits (the size of the mantissa in a 64-bit IEEE Float) cannot be converted exactly to double, and vice versa; therefore, NI-XNET does not support this. This property is required. If the property does not contain a valid value, and you create an XNET session that uses this signal, the session returns an error. To ensure that the property contains a valid value, you can do one of the following: * Use a database file (or alias) to create the session. The file formats require a valid value in the text for this property. * Set a value at runtime using this property. This is needed when you create your own in-memory database (*:memory:*) rather than use a file. The property does not contain a default in this case, so you must set a valid value prior to creating a session. """ return _props.get_signal_num_bits(self._handle) @num_bits.setter def num_bits(self, value): # type: (int) -> None _props.set_signal_num_bits(self._handle, value) @property def pdu(self): # type: () -> _pdu.Pdu """:any:`Pdu`: Returns to the signal's parent PDU. The parent PDU is defined when the signal object is created. You cannot change it afterwards. """ from nixnet.database import _pdu # NOQA: F811 ref = _props.get_signal_pdu_ref(self._handle) return _pdu.Pdu(_handle=ref) @property def scale_fac(self): # type: () -> float """float: Get or set factor `a` for linear scaling `ax+b`. Linear scaling is applied to all signals with the IEEE Float data type, unsigned and signed. For identical scaling 1.0x+0.0, NI-XNET optimized scaling routines do not perform the multiplication and addition """ return _props.get_signal_scale_fac(self._handle) @scale_fac.setter def scale_fac(self, value): # type: (float) -> None _props.set_signal_scale_fac(self._handle, value) @property def scale_off(self): # type: () -> float """float: Get or set offset `b` for linear scaling `ax+b`. Linear scaling is applied to all signals with the IEEE Float data type, unsigned and signed. For identical scaling 1.0x+0.0, NI-XNET optimized scaling routines do not perform the multiplication and addition """ return _props.get_signal_scale_off(self._handle) @scale_off.setter def scale_off(self, value): # type: (float) -> None _props.set_signal_scale_off(self._handle, value) @property def start_bit(self): """int: Get or set the least significant signal bit position in the frame payload. This property determines the signal starting point in the frame. For the integer data type (signed and unsigned), it means the binary signal representation least significant bit position. For IEEE Float signals, it means the mantissa least significant bit. The NI-XNET Database Editor shows a graphical overview of the frame. It enumerates the frame bytes on the left and the byte bits on top. The bit number in the frame is calculated as byte number x 8 + bit number. The maximum bit number in a CAN or LIN frame is 63 (7 x 8 + 7); the maximum bit number in a FlexRay frame is 2031 (253 x 8 + 7). .. image:: frameoverviewsignalstartingbit12.gif **Frame Overview in the NI-XNET Database Editor with a Signal Starting in Bit 12** This property is required. If the property does not contain a valid value, and you create an XNET session that uses this signal, the session returns an error. To ensure that the property contains a valid value, you can do one of the following: * Use a database file (or alias) to create the session. The file formats require a valid value in the text for this property. * Set a value at runtime using this property. This is needed when you create your own in-memory database (*:memory:*) rather than use a file. The property does not contain a default in this case, so you must set a valid value prior to creating a session. """ return _props.get_signal_start_bit(self._handle) @start_bit.setter def start_bit(self, value): # type: (typing.Any) -> typing.Any _props.set_signal_start_bit(self._handle, value) @property def unit(self): # type: () -> typing.Text """str: Get or set the signal value unit. NI-XNET does not use the unit internally for calculations. You can use the string to display the signal value along with the unit. """ return _props.get_signal_unit(self._handle) @unit.setter def unit(self, value): # type: (typing.Text) -> None _props.set_signal_unit(self._handle, value) @property def mux_is_data_mux(self): # type: () -> bool """bool: Get or set whether this signal is a multiplexer signal. A frame containing a multiplexer value is called a multiplexed frame. A multiplexer defines an area within the frame to contain different information (dynamic signals) depending on the multiplexer signal value. Dynamic signals with a different multiplexer value (defined in a different subframe) can share bits in the frame payload. The multiplexer signal value determines which dynamic signals are transmitted in the given frame. To define dynamic signals in the frame transmitted with a given multiplexer value, you first must create a subframe in this frame and set the multiplexer value in the subframe. Then you must create dynamic signals using :any:`SubFrame.dyn_signals` to create child signals of this subframe. Multiplexer signals may not overlap other static or dynamic signals in the frame. Dynamic signals may overlap other dynamic signals when they have a different multiplexer value. A frame may contain only one multiplexer signal. The multiplexer signal is not scaled. Scaling factor and offset do not apply. In NI-CAN, the multiplexer signal was called mode channel. """ return _props.get_signal_mux_is_data_mux(self._handle) @mux_is_data_mux.setter def mux_is_data_mux(self, value): # type: (bool) -> None _props.set_signal_mux_is_data_mux(self._handle, value) @property def mux_is_dynamic(self): # type: () -> bool """bool: returns whether this signal is a dynamic signal. Use this property to determine if a signal is static or dynamic. Dynamic signals are transmitted in the frame when the multiplexer signal in the frame has a given value specified in the subframe. Use the :any:`Signal.mux_value` property to determine with which multiplexer value the dynamic signal is transmitted. This property is read only. To create a dynamic signal, create the signal object as a child of a subframe instead of a frame. The dynamic signal cannot be changed to a static signal afterwards. In NI-CAN, dynamic signals were called mode-dependent signals. """ return _props.get_signal_mux_is_dynamic(self._handle) @property def mux_value(self): # type: () -> int """int: Returns the multiplexer value of a dynamic signal. The multiplexer value applies to dynamic signals only (when :any:`Signal.mux_is_dynamic` is ``True``). This property defines which multiplexer value is transmitted in the multiplexer signal when this dynamic signal is transmitted in the frame. The multiplexer value is determined in the subframe. All dynamic signals that are children of the same subframe object use the same multiplexer value. Dynamic signals with the same multiplexer value may not overlap each other, the multiplexer signal, or static signals. """ return _props.get_signal_mux_value(self._handle) @property def mux_subfrm(self): # type: () -> _subframe.SubFrame """:any:`SubFrame`: Returns the subframe parent. This property is valid only for dynamic signals that have a subframe parent. For static signals or the multiplexer signal, this property raises an :any:`XnetError` exception. Raises: :any:`XnetError`: The signal does not have a subframe parent. """ from nixnet.database import _subframe # NOQA: F811 ref = _props.get_signal_mux_subfrm_ref(self._handle) if ref == 0: _errors.raise_xnet_error(_cconsts.NX_ERR_FRAME_NOT_FOUND) return _subframe.SubFrame(_handle=ref)
mit
b19ebc3b3e3ceda99160c5f3175a0343
38.410156
119
0.647884
4.349644
false
false
false
false
cwacek/python-jsonschema-objects
python_jsonschema_objects/wrapper_types.py
1
11522
import collections import logging import six from python_jsonschema_objects import util from python_jsonschema_objects.validators import registry, ValidationError from python_jsonschema_objects.util import lazy_format as fmt logger = logging.getLogger(__name__) class ArrayWrapper(collections.abc.MutableSequence): """A wrapper for array-like structures. This implements all of the array like behavior that one would want, with a dirty-tracking mechanism to avoid constant validation costs. """ @property def strict(self): return getattr(self, "_strict_", False) def __len__(self): return len(self.data) def mark_or_revalidate(self): if self.strict: self.validate() else: self._dirty = True def __delitem__(self, index): self.data.pop(index) self.mark_or_revalidate() def insert(self, index, value): self.data.insert(index, value) self.mark_or_revalidate() def __setitem__(self, index, value): self.data[index] = value self.mark_or_revalidate() def __getitem__(self, idx): return self.typed_elems[idx] def __eq__(self, other): if isinstance(other, ArrayWrapper): return self.for_json() == other.for_json() else: return self.for_json() == other def __init__(self, ary): """Initialize a wrapper for the array Args: ary: (list-like, or ArrayWrapper) """ """ Marks whether or not the underlying array has been modified """ self._dirty = True """ Holds a typed copy of the array """ self._typed = None if isinstance(ary, (list, tuple, collections.abc.Sequence)): self.data = ary else: raise TypeError("Invalid value given to array validator: {0}".format(ary)) logger.debug(fmt("Initializing ArrayWrapper {} with {}", self, ary)) @property def typed_elems(self): logger.debug(fmt("Accessing typed_elems of ArrayWrapper {} ", self)) if self._typed is None or self._dirty is True: self.validate() return self._typed def __repr__(self): return "<%s=%s>" % (self.__class__.__name__, str(self.data)) @classmethod def from_json(cls, jsonmsg): import json msg = json.loads(jsonmsg) obj = cls(msg) obj.validate() return obj def serialize(self): enc = util.ProtocolJSONEncoder() return enc.encode(self.typed_elems) def for_json(self): from python_jsonschema_objects import classbuilder out = [] for item in self.typed_elems: if isinstance( item, (classbuilder.ProtocolBase, classbuilder.LiteralValue, ArrayWrapper), ): out.append(item.for_json()) else: out.append(item) return out def validate(self): if self.strict or self._dirty: self.validate_items() self.validate_length() self.validate_uniqueness() return True def validate_uniqueness(self): if getattr(self, "uniqueItems", False) is True: testset = set(repr(item) for item in self.data) if len(testset) != len(self.data): raise ValidationError( "{0} has duplicate elements, but uniqueness required".format( self.data ) ) def validate_length(self): if getattr(self, "minItems", None) is not None: if len(self.data) < self.minItems: raise ValidationError( "{1} has too few elements. Wanted {0}.".format( self.minItems, self.data ) ) if getattr(self, "maxItems", None) is not None: if len(self.data) > self.maxItems: raise ValidationError( "{1} has too many elements. Wanted {0}.".format( self.maxItems, self.data ) ) def validate_items(self): """Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array """ logger.debug(fmt("Validating {}", self)) from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not isinstance(type_checks, (tuple, list)): # we were given items = {'type': 'blah'} ; thus ensure the type for all data. type_checks = [type_checks] * len(self.data) elif len(type_checks) > len(self.data): raise ValidationError( "{1} does not have sufficient elements to validate against {0}".format( self.__itemtype__, self.data ) ) typed_elems = [] for elem, typ in zip(self.data, type_checks): if isinstance(typ, dict): for param, paramval in six.iteritems(typ): validator = registry(param) if validator is not None: validator(paramval, elem, typ) typed_elems.append(elem) elif util.safe_issubclass(typ, classbuilder.LiteralValue): val = typ(elem) val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, classbuilder.ProtocolBase): if not isinstance(elem, typ): try: if isinstance( elem, (six.string_types, six.integer_types, float) ): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError( "'{0}' is not a valid value for '{1}': {2}".format( elem, typ, e ) ) else: val = elem val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, ArrayWrapper): val = typ(elem) val.validate() typed_elems.append(val) elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError( "'{0}' is not a valid value for '{1}': {2}".format(elem, typ, e) ) else: val.validate() typed_elems.append(val) self._dirty = False self._typed = typed_elems return typed_elems @staticmethod def create(name, item_constraint=None, **addl_constraints): """Create an array validator based on the passed in constraints. If item_constraint is a tuple, it is assumed that tuple validation is being performed. If it is a class or dictionary, list validation will be performed. Classes are assumed to be subclasses of ProtocolBase, while dictionaries are expected to be basic types ('string', 'number', ...). addl_constraints is expected to be key-value pairs of any of the other constraints permitted by JSON Schema v4. """ logger.debug( fmt( "Constructing ArrayValidator with {} and {}", item_constraint, addl_constraints, ) ) from python_jsonschema_objects import classbuilder klassbuilder = addl_constraints.pop( "classbuilder", None ) # type: python_jsonschema_objects.classbuilder.ClassBuilder props = {} if item_constraint is not None: if isinstance(item_constraint, (tuple, list)): for i, elem in enumerate(item_constraint): isdict = isinstance(elem, (dict,)) isklass = isinstance(elem, type) and util.safe_issubclass( elem, (classbuilder.ProtocolBase, classbuilder.LiteralValue) ) if not any([isdict, isklass]): raise TypeError( "Item constraint (position {0}) is not a schema".format(i) ) elif isinstance( item_constraint, (classbuilder.TypeProxy, classbuilder.TypeRef) ): pass elif util.safe_issubclass(item_constraint, ArrayWrapper): pass else: isdict = isinstance(item_constraint, (dict,)) isklass = isinstance(item_constraint, type) and util.safe_issubclass( item_constraint, (classbuilder.ProtocolBase, classbuilder.LiteralValue), ) if not any([isdict, isklass]): raise TypeError("Item constraint is not a schema") if isdict and "$ref" in item_constraint: if klassbuilder is None: raise TypeError( "Cannot resolve {0} without classbuilder".format( item_constraint["$ref"] ) ) item_constraint = klassbuilder.resolve_type( item_constraint["$ref"], name ) elif isdict and item_constraint.get("type") == "array": # We need to create a sub-array validator. item_constraint = ArrayWrapper.create( name + "#sub", item_constraint=item_constraint["items"], addl_constraints=item_constraint, ) elif isdict and "oneOf" in item_constraint: # We need to create a TypeProxy validator uri = "{0}_{1}".format(name, "<anonymous_list_type>") type_array = klassbuilder.construct_objects( item_constraint["oneOf"], uri ) item_constraint = classbuilder.TypeProxy(type_array) elif isdict and item_constraint.get("type") == "object": """ We need to create a ProtocolBase object for this anonymous definition""" uri = "{0}_{1}".format(name, "<anonymous_list_type>") item_constraint = klassbuilder.construct(uri, item_constraint) props["__itemtype__"] = item_constraint strict = addl_constraints.pop("strict", False) props["_strict_"] = strict props.update(addl_constraints) validator = type(str(name), (ArrayWrapper,), props) return validator
mit
fd0c49a9fb07748dcba0d412b2958d17
34.343558
96
0.518486
4.837112
false
false
false
false
cwacek/python-jsonschema-objects
test/test_regression_214.py
1
2381
import json import pytest import python_jsonschema_objects as pjo schema = { "$schema": "http://json-schema.org/draft-07/schema", "title": "myschema", "type": "object", "definitions": { "MainObject": { "title": "Main Object", "additionalProperties": False, "type": "object", "properties": { "location": { "title": "location", "type": ["object", "string"], "oneOf": [ {"$ref": "#/definitions/UNIQUE_STRING"}, {"$ref": "#/definitions/Location"}, ], } }, }, "Location": { "title": "Location", "description": "A Location represents a span on a specific sequence.", "type": "object", "oneOf": [ {"$ref": "#/definitions/Location1"}, {"$ref": "#/definitions/Location2"}, ], "discriminator": {"propertyName": "type"}, }, "Location1": { "additionalProperties": False, "type": "object", "properties": { "type": { "type": "string", "enum": ["Location1"], "default": "Location1", } }, }, "Location2": { "additionalProperties": False, "type": "object", "properties": { "type": { "type": "string", "enum": ["Location2"], "default": "Location2", } }, }, "UNIQUE_STRING": { "additionalProperties": False, "type": "string", "pattern": "^\\w[^:]*:.+$", }, }, } @pytest.fixture def schema_json(): return schema def test_nested_oneofs_still_work(schema_json): builder = pjo.ObjectBuilder(schema_json) ns = builder.build_classes() obj1 = ns.MainObject(**{"location": {"type": "Location1"}}) obj2 = ns.MainObject(**{"location": {"type": "Location2"}}) obj3 = ns.MainObject(**{"location": "unique:12"}) assert obj1.location.type == "Location1" assert obj2.location.type == "Location2" assert obj3.location == "unique:12"
mit
f3c325dd43e366e99cebc17648054a97
28.395062
82
0.432591
4.401109
false
false
false
false
rollbar/pyrollbar
rollbar/contrib/fastapi/routing.py
1
3401
__all__ = ['add_to'] import logging import sys from typing import Callable, Optional, Type, Union from fastapi import APIRouter, FastAPI, __version__ from fastapi.routing import APIRoute try: from fastapi import Request, Response except ImportError: # Added in FastAPI v0.51.0 from starlette.requests import Request from starlette.responses import Response import rollbar from .utils import fastapi_min_version, get_installed_middlewares, has_bare_routing from rollbar.contrib.asgi.integration import integrate from rollbar.contrib.starlette.requests import store_current_request from rollbar.lib._async import RollbarAsyncError, try_report log = logging.getLogger(__name__) @fastapi_min_version('0.41.0') @integrate(framework_name=f'fastapi {__version__}') def add_to(app_or_router: Union[FastAPI, APIRouter]) -> Optional[Type[APIRoute]]: """ Adds RollbarLoggingRoute handler to the router app. This is the recommended way for integration with FastAPI. Alternatively to using middleware, the handler may fill more data in the payload (e.g. request body). app_or_router: FastAPI app or router Note: The route handler must be added before adding user routes Requirements: FastAPI v0.41.0+ Example usage: from fastapi import FastAPI from rollbar.contrib.fastapi import add_to as rollbar_add_to app = FastAPI() rollbar_add_to(app) """ if not has_bare_routing(app_or_router): log.error( 'RollbarLoggingRoute must to be added to a bare router' ' (before adding routes). See docs for more details.' ) return None installed_middlewares = get_installed_middlewares(app_or_router) if installed_middlewares: log.warning( f'Detected middleware installed {installed_middlewares}' ' while loading Rollbar route handler.' ' This can cause in duplicate occurrences.' ) if isinstance(app_or_router, FastAPI): _add_to_app(app_or_router) elif isinstance(app_or_router, APIRouter): _add_to_router(app_or_router) else: log.error('Error adding RollbarLoggingRoute to application.') return None return RollbarLoggingRoute class RollbarLoggingRoute(APIRoute): def get_route_handler(self) -> Callable: router_handler = super().get_route_handler() async def rollbar_route_handler(request: Request) -> Response: try: store_current_request(request) return await router_handler(request) except Exception: # FastAPI requires the `python-multipart` package to parse the content if not request._stream_consumed: await request.body() await request.form() exc_info = sys.exc_info() try: await try_report(exc_info, request) except RollbarAsyncError: log.warning( 'Failed to report asynchronously. Trying to report synchronously.' ) rollbar.report_exc_info(exc_info, request) raise return rollbar_route_handler def _add_to_app(app): app.router.route_class = RollbarLoggingRoute def _add_to_router(router): router.route_class = RollbarLoggingRoute
mit
ff48591d246d8e2a32883e2440d41bd9
29.63964
90
0.653043
4.073054
false
false
false
false
rollbar/pyrollbar
rollbar/lib/traverse.py
3
4205
import logging try: # Python 3 from collections.abc import Mapping from collections.abc import Sequence except ImportError: # Python 2.7 from collections import Mapping from collections import Sequence from rollbar.lib import binary_type, iteritems, string_types, circular_reference_label CIRCULAR = -1 DEFAULT = 0 MAPPING = 1 TUPLE = 2 NAMEDTUPLE = 3 LIST = 4 SET = 5 STRING = 6 log = logging.getLogger(__name__) def _noop_circular(a, **kw): return circular_reference_label(a, ref_key=kw.get('ref_key')) def _noop(a, **_): return a def _noop_tuple(a, **_): return tuple(a) def _noop_namedtuple(a, **_): return a._make(a) def _noop_list(a, **_): return list(a) def _noop_set(a, **_): return set(a) def _noop_mapping(a, **_): return dict(a) _default_handlers = { CIRCULAR: _noop_circular, DEFAULT: _noop, STRING: _noop, TUPLE: _noop_tuple, NAMEDTUPLE: _noop_namedtuple, LIST: _noop_list, SET: _noop_set, MAPPING: _noop_mapping, } def get_type(obj): if isinstance(obj, (string_types, binary_type)): return STRING if isinstance(obj, Mapping): return MAPPING if isinstance(obj, tuple): if hasattr(obj, '_fields'): return NAMEDTUPLE return TUPLE if isinstance(obj, set): return SET if isinstance(obj, Sequence): return LIST return DEFAULT def traverse(obj, key=(), string_handler=_default_handlers[STRING], tuple_handler=_default_handlers[TUPLE], namedtuple_handler=_default_handlers[NAMEDTUPLE], list_handler=_default_handlers[LIST], set_handler=_default_handlers[SET], mapping_handler=_default_handlers[MAPPING], default_handler=_default_handlers[DEFAULT], circular_reference_handler=_default_handlers[CIRCULAR], allowed_circular_reference_types=None, memo=None, **custom_handlers): memo = memo or {} obj_id = id(obj) obj_type = get_type(obj) ref_key = memo.get(obj_id) if ref_key: if not allowed_circular_reference_types or not isinstance(obj, allowed_circular_reference_types): return circular_reference_handler(obj, key=key, ref_key=ref_key) memo[obj_id] = key kw = { 'string_handler': string_handler, 'tuple_handler': tuple_handler, 'namedtuple_handler': namedtuple_handler, 'list_handler': list_handler, 'set_handler': set_handler, 'mapping_handler': mapping_handler, 'default_handler': default_handler, 'circular_reference_handler': circular_reference_handler, 'allowed_circular_reference_types': allowed_circular_reference_types, 'memo': memo } kw.update(custom_handlers) try: if obj_type is STRING: return string_handler(obj, key=key) elif obj_type is TUPLE: return tuple_handler(tuple(traverse(elem, key=key + (i,), **kw) for i, elem in enumerate(obj)), key=key) elif obj_type is NAMEDTUPLE: return namedtuple_handler(obj._make(traverse(v, key=key + (k,), **kw) for k, v in iteritems(obj._asdict())), key=key) elif obj_type is LIST: return list_handler(list(traverse(elem, key=key + (i,), **kw) for i, elem in enumerate(obj)), key=key) elif obj_type is SET: return set_handler(set(traverse(elem, key=key + (i,), **kw) for i, elem in enumerate(obj)), key=key) elif obj_type is MAPPING: return mapping_handler(dict((k, traverse(v, key=key + (k,), **kw)) for k, v in iteritems(obj)), key=key) elif obj_type is DEFAULT: for handler_type, handler in iteritems(custom_handlers): if isinstance(obj, handler_type): return handler(obj, key=key) except: # use the default handler for unknown object types log.debug("Exception while traversing object using type-specific " "handler. Switching to default handler.", exc_info=True) return default_handler(obj, key=key) __all__ = ['traverse']
mit
11e9e266e872cef00726ef4ac7b5039c
26.664474
129
0.612366
3.704846
false
false
false
false
meraki-analytics/cassiopeia
cassiopeia/core/status.py
1
5417
from typing import List, Union from merakicommons.cache import lazy from merakicommons.container import searchable, SearchableList from ..data import Region, Platform from .common import CoreData, CassiopeiaObject, CassiopeiaGhost, ghost_load_on ############## # Data Types # ############## class TranslationData(CoreData): _renamed = {"updated_at": "updated"} class MessageData(CoreData): _renamed = {"created_at": "created", "updated_at": "updated"} def __call__(self, **kwargs): if "translations" in kwargs: self.translations = [ TranslationData(**translation) for translation in kwargs.pop("translations") ] super().__call__(**kwargs) return self class IncidentData(CoreData): _renamed = {"created_at": "created"} def __call__(self, **kwargs): if "updates" in kwargs: self.updates = [MessageData(**update) for update in kwargs.pop("updates")] super().__call__(**kwargs) return self class ServiceData(CoreData): _renamed = {} def __call__(self, **kwargs): if "incidents" in kwargs: self.incidents = [ IncidentData(**incident) for incident in kwargs.pop("incidents") ] super().__call__(**kwargs) return self class ShardStatusData(CoreData): _renamed = {"region_tag": "platform"} def __call__(self, **kwargs): if "services" in kwargs: self.services = [ ServiceData(**service) for service in kwargs.pop("services") ] super().__call__(**kwargs) return self ############## # Core Types # ############## @searchable({}) class Translation(CassiopeiaObject): _data_types = {TranslationData} @property def locale(self) -> str: return self._data[TranslationData].locale @property def content(self) -> str: return self._data[TranslationData].content @property def updated(self) -> str: return self._data[TranslationData].updated class Message(CassiopeiaObject): _data_types = {MessageData} @property def severity(self) -> str: return self._data[MessageData].severity @property def author(self) -> str: return self._data[MessageData].author @property def created(self) -> str: return self._data[MessageData].created @property def translations(self) -> List[Translation]: return SearchableList( [Translation(trans) for trans in self._data[MessageData].translations] ) @property def updated(self) -> str: return self._data[MessageData].updated @property def content(self) -> str: return self._data[MessageData].content @property def id(self) -> str: return self._data[MessageData].id class Incident(CassiopeiaObject): _data_types = {IncidentData} @property def active(self) -> bool: return self._data[IncidentData].active @property def created(self) -> str: return self._data[IncidentData].created @property def id(self) -> int: return self._data[IncidentData].id @property def updates(self) -> List[Message]: return SearchableList( [Message.from_data(message) for message in self._data[IncidentData].updates] ) class Service(CassiopeiaObject): _data_types = {ServiceData} @property def status(self) -> str: return self._data[ServiceData].status @property def incidents(self) -> List[Incident]: return SearchableList( [Incident.from_data(inc) for inc in self._data[ServiceData].incidents] ) @property def name(self) -> str: return self._data[ServiceData].name @property def slug(self) -> str: return self._data[ServiceData].slug @searchable({}) class ShardStatus(CassiopeiaGhost): _data_types = {ShardStatusData} def __init__(self, region: Union[Region, str] = None): kwargs = {"region": region} super().__init__(**kwargs) def __get_query__(self): return {"region": self.region, "platform": self.platform} @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on @lazy def region(self) -> Region: return Region(self._data[ShardStatusData].region) @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on @lazy def platform(self) -> Platform: return self.region.platform @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on def name(self) -> str: return self._data[ShardStatusData].name @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on def hostname(self) -> str: return self._data[ShardStatusData].hostname @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on def services(self) -> List[Service]: return SearchableList( [ Service.from_data(service) for service in self._data[ShardStatusData].services ] ) @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on def slug(self) -> str: return self._data[ShardStatusData].slug @CassiopeiaGhost.property(ShardStatusData) @ghost_load_on def locales(self) -> List[str]: return self._data[ShardStatusData].locales
mit
22a57223d88b8c1b8ae75e8afc8e8de0
23.963134
88
0.613808
3.908369
false
false
false
false
rollbar/pyrollbar
rollbar/lib/events.py
2
1970
EXCEPTION_INFO = 'exception_info' MESSAGE = 'message' PAYLOAD = 'payload' _event_handlers = { EXCEPTION_INFO: [], MESSAGE: [], PAYLOAD: [] } def _check_type(typ): if typ not in _event_handlers: raise ValueError('Unknown type: %s. Must be one of %s' % (typ, _event_handlers.keys())) def _add_handler(typ, handler_fn, pos): _check_type(typ) pos = pos if pos is not None else -1 handlers = _event_handlers[typ] try: handlers.index(handler_fn) except ValueError: handlers.insert(pos, handler_fn) def _remove_handler(typ, handler_fn): _check_type(typ) handlers = _event_handlers[typ] try: index = handlers.index(handler_fn) handlers.pop(index) except ValueError: pass def _on_event(typ, target, **kw): _check_type(typ) ref = target for handler in _event_handlers[typ]: result = handler(ref, **kw) if result is False: return False ref = result return ref # Add/remove event handlers def add_exception_info_handler(handler_fn, pos=None): _add_handler(EXCEPTION_INFO, handler_fn, pos) def remove_exception_info_handler(handler_fn): _remove_handler(EXCEPTION_INFO, handler_fn) def add_message_handler(handler_fn, pos=None): _add_handler(MESSAGE, handler_fn, pos) def remove_message_handler(handler_fn): _remove_handler(MESSAGE, handler_fn) def add_payload_handler(handler_fn, pos=None): _add_handler(PAYLOAD, handler_fn, pos) def remove_payload_handler(handler_fn): _remove_handler(PAYLOAD, handler_fn) # Event handler processing def on_exception_info(exc_info, **kw): return _on_event(EXCEPTION_INFO, exc_info, **kw) def on_message(message, **kw): return _on_event(MESSAGE, message, **kw) def on_payload(payload, **kw): return _on_event(PAYLOAD, payload, **kw) # Misc def reset(): for handlers in _event_handlers.values(): del handlers[:]
mit
f71225c093c548739fbf38c28ce87957
18.89899
95
0.645685
3.299832
false
false
false
false
meraki-analytics/cassiopeia
cassiopeia/_configuration/settings.py
1
7283
from typing import TypeVar, Type, Dict, Union, List import logging import importlib import inspect import copy from datapipelines import ( DataPipeline, DataSink, DataSource, CompositeDataTransformer, DataTransformer, ) from ..data import Region, Platform T = TypeVar("T") logging.basicConfig( format="%(asctime)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.WARNING, ) def create_pipeline(service_configs: Dict, verbose: int = 0) -> DataPipeline: transformers = [] # Always use the Riot API transformers from ..transformers import __transformers__ as riotapi_transformer transformers.extend(riotapi_transformer) # Add sources / sinks by name from config services = [] for store_name, config in service_configs.items(): package = config.pop("package", None) if package is None: package = "cassiopeia.datastores" module = importlib.import_module(name=package) store_cls = getattr(module, store_name) store = store_cls(**config) services.append(store) service_transformers = getattr(module, "__transformers__", []) transformers.extend(service_transformers) from ..datastores import Cache, MerakiAnalyticsCDN, LolWikia # Automatically insert the ghost store if it isn't there from ..datastores import UnloadedGhostStore found = False for datastore in services: if isinstance(datastore, UnloadedGhostStore): found = True break if not found: if any(isinstance(service, Cache) for service in services): # Find the cache and insert the ghost store directly after it for i, datastore in enumerate(services): if isinstance(datastore, Cache): services.insert(i + 1, UnloadedGhostStore()) break else: # Insert the ghost store at the beginning of the pipeline services.insert(0, UnloadedGhostStore()) services.append(MerakiAnalyticsCDN()) services.append(LolWikia()) pipeline = DataPipeline(services, transformers) # Manually put the cache on the pipeline. for datastore in services: if isinstance(datastore, Cache): pipeline._cache = datastore break else: pipeline._cache = None if verbose > 0: for service in services: print("Service:", service) if verbose > 1: if isinstance(service, DataSource): for p in service.provides: print(" Provides:", p) if isinstance(service, DataSink): for p in service.accepts: print(" Accepts:", p) if verbose > 2: for transformer in transformers: for t in transformer.transforms.items(): print("Transformer:", t) print() return pipeline def register_transformer_conversion(transformer: DataTransformer, from_type, to_type): # Find the method that takes a `from_type` and returns a `to_type` and register it methods = inspect.getmembers(transformer, predicate=inspect.ismethod) for name, method in methods: annotations = copy.copy(method.__annotations__) return_type = annotations.pop("return") annotations.pop("context", None) try: if to_type is return_type and from_type in annotations.values(): transformer.transform.register(from_type, to_type)( method.__func__ ).__get__(transformer, transformer.__class__) break except TypeError: continue else: raise RuntimeError( "Could not find method to register: {} to {} in {}.".format( from_type, to_type, transformer ) ) def get_default_config(): return { "global": {"version_from_match": "patch"}, "plugins": {}, "pipeline": { "Cache": {}, "DDragon": {}, "RiotAPI": {"api_key": "RIOT_API_KEY"}, }, "logging": { "print_calls": True, "print_riot_api_key": False, "default": "WARNING", "core": "WARNING", }, } class Settings(object): def __init__(self, settings): _defaults = get_default_config() globals_ = settings.get("global", _defaults["global"]) self.__version_from_match = globals_.get( "version_from_match", _defaults["global"]["version_from_match"] ) # Valid json values are: "version", "patch", and null self.__plugins = settings.get("plugins", _defaults["plugins"]) self.__pipeline_args = settings.get("pipeline", _defaults["pipeline"]) self.__pipeline = None # type: DataPipeline logging_config = settings.get("logging", _defaults["logging"]) self.__default_print_calls = logging_config.get( "print_calls", _defaults["logging"]["print_calls"] ) self.__default_print_riot_api_key = logging_config.get( "print_riot_api_key", _defaults["logging"]["print_riot_api_key"] ) for name in ["default", "core"]: logger = logging.getLogger(name) level = logging_config.get(name, _defaults["logging"][name]) logger.setLevel(level) for handler in logger.handlers: handler.setLevel(level) @property def pipeline(self) -> DataPipeline: if self.__pipeline is None: self.__pipeline = create_pipeline( service_configs=self.__pipeline_args, verbose=0 ) return self.__pipeline @property def version_from_match(self): return self.__version_from_match @property def plugins(self): return self.__plugins def set_riot_api_key(self, key): from ..datastores.riotapi import RiotAPI for sources in self.pipeline._sources: for source in sources: if isinstance(source, RiotAPI): source.set_api_key(key) def clear_sinks(self, type: Type[T] = None): types = {type} if type is not None: from ..core.common import CoreData, CassiopeiaObject if issubclass(type, CassiopeiaObject): for t in type._data_types: types.add(t) types.add(t._dto_type) elif issubclass(type, CoreData): types.add(type._dto_type) for sink in self.pipeline._sinks: for type in types: sink.clear(type) def expire_sinks(self, type: Type[T] = None): types = {type} if type is not None: from ..core.common import CoreData, CassiopeiaObject if issubclass(type, CassiopeiaObject): for t in type._data_types: types.add(t) types.add(t._dto_type) elif issubclass(type, CoreData): types.add(type._dto_type) for sink in self.pipeline._sinks: for type in types: sink.expire(type)
mit
691a9586f518157bdeabdc44d2b86b06
31.954751
86
0.574077
4.312019
false
true
false
false
meraki-analytics/cassiopeia
cassiopeia/datastores/cache.py
1
53137
from typing import Type, Mapping, Any, Iterable, TypeVar, Tuple, Callable, Generator import datetime from datapipelines import ( DataSource, DataSink, PipelineContext, validate_query, NotFoundError, ) from merakicommons.cache import Cache as CommonsCache from . import uniquekeys from ..core.staticdata.champion import ( ChampionData, ChampionListData, Champion, Champions, ) from ..core.staticdata.rune import RuneData, RuneListData, Rune, Runes from ..core.staticdata.item import ItemData, ItemListData, Item, Items from ..core.staticdata.summonerspell import ( SummonerSpellData, SummonerSpellListData, SummonerSpell, SummonerSpells, ) from ..core.staticdata.map import MapData, MapListData, Map, Maps from ..core.staticdata.realm import RealmData, Realms from ..core.staticdata.profileicon import ( ProfileIconData, ProfileIconListData, ProfileIcon, ProfileIcons, ) from ..core.staticdata.language import LanguagesData, Locales from ..core.staticdata.languagestrings import LanguageStringsData, LanguageStrings from ..core.staticdata.version import VersionListData, Versions from ..core.championmastery import ( ChampionMasteryData, ChampionMasteryListData, ChampionMastery, ChampionMasteries, ) from ..core.league import ( MasterLeagueListData, GrandmasterLeagueListData, ChallengerLeagueListData, LeagueSummonerEntries, League, ChallengerLeague, GrandmasterLeague, MasterLeague, LeagueEntries, ) from ..core.match import MatchData, TimelineData, Match, Timeline from ..core.summoner import SummonerData, Summoner from ..core.status import ShardStatusData, ShardStatus from ..core.spectator import ( CurrentGameInfoData, FeaturedGamesData, CurrentMatch, FeaturedMatches, ) from ..core.champion import ChampionRotationData, ChampionRotation T = TypeVar("T") default_expirations = { ChampionRotationData: datetime.timedelta(hours=6), Realms: datetime.timedelta(hours=6), Versions: datetime.timedelta(hours=6), Champion: datetime.timedelta(days=20), Rune: datetime.timedelta(days=20), Item: datetime.timedelta(days=20), SummonerSpell: datetime.timedelta(days=20), Map: datetime.timedelta(days=20), ProfileIcon: datetime.timedelta(days=20), Locales: datetime.timedelta(days=20), LanguageStrings: datetime.timedelta(days=20), SummonerSpells: datetime.timedelta(days=20), Items: datetime.timedelta(days=20), Champions: datetime.timedelta(days=20), Runes: datetime.timedelta(days=20), Maps: datetime.timedelta(days=20), ProfileIcons: datetime.timedelta(days=20), ChampionMastery: datetime.timedelta(days=7), ChampionMasteries: datetime.timedelta(days=7), LeagueSummonerEntries: datetime.timedelta(hours=6), League: datetime.timedelta(hours=6), ChallengerLeague: datetime.timedelta(hours=6), GrandmasterLeague: datetime.timedelta(hours=6), MasterLeague: datetime.timedelta(hours=6), Match: datetime.timedelta(days=3), Timeline: datetime.timedelta(days=1), Summoner: datetime.timedelta(days=1), ShardStatus: datetime.timedelta(hours=1), CurrentMatch: datetime.timedelta(hours=0.5), FeaturedMatches: datetime.timedelta(hours=0.5), } class Cache(DataSource, DataSink): def __init__(self, expirations: Mapping[type, float] = None) -> None: self._cache = CommonsCache() self._expirations = ( dict(expirations) if expirations is not None else default_expirations ) for key, value in list(self._expirations.items()): if isinstance(key, str): new_key = globals()[key] self._expirations[new_key] = self._expirations.pop(key) key = new_key if value != -1 and isinstance(value, datetime.timedelta): self._expirations[key] = value.seconds + 24 * 60 * 60 * value.days @DataSource.dispatch def get( self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None ) -> T: pass @DataSource.dispatch def get_many( self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None ) -> Iterable[T]: pass @DataSink.dispatch def put(self, type: Type[T], item: T, context: PipelineContext = None) -> None: pass @DataSink.dispatch def put_many( self, type: Type[T], items: Iterable[T], context: PipelineContext = None ) -> None: pass def _get( self, type: Type[T], query: Mapping[str, Any], key_function: Callable[[Mapping[str, Any]], Any], context: PipelineContext = None, ) -> T: keys = key_function(query) for key in keys: try: return self._cache.get(type, key) except KeyError: pass else: raise NotFoundError def _get_many( self, type: Type[T], query: Mapping[str, Any], key_generator: Callable[[Mapping[str, Any]], Any], context: PipelineContext = None, ) -> Generator[T, None, None]: for keys in key_generator(query): for key in keys: try: yield self._cache.get(type, key) except KeyError: pass else: raise NotFoundError @staticmethod def _put_many_generator( items: Iterable[T], key_function: Callable[[T], Any] ) -> Generator[Tuple[Any, T], None, None]: for item in items: for key in key_function(item): yield key, item def _put( self, type: Type[T], item: T, key_function: Callable[[T], Any], context: PipelineContext = None, ) -> None: try: expire_seconds = self._expirations[type] except KeyError: expire_seconds = -1 if expire_seconds != 0: keys = key_function(item) for key in keys: self._cache.put(type, key, item, expire_seconds) def _put_many( self, type: Type[T], items: Iterable[T], key_function: Callable[[T], Any], context: PipelineContext = None, ) -> None: expire_seconds = self._expirations.get(type, default_expirations[type]) for key, item in Cache._put_many_generator(items, key_function): self._cache.put(type, key, item, expire_seconds) def clear(self, type: Type[T] = None): if type is None: for key in self._cache._data: self._cache._data[key].clear() else: self._cache._data[type].clear() def expire(self, type: Type[T] = None): self._cache.expire(type) ##################### # Champion Rotation # ##################### # Champion Rotation Data @get.register(ChampionRotationData) @validate_query( uniquekeys.validate_champion_rotation_query, uniquekeys.convert_region_to_platform, ) def get_champion_rotation( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ChampionRotationData: return self._get( ChampionRotationData, query, uniquekeys.for_champion_rotation_query, context ) @get_many.register(ChampionRotationData) @validate_query( uniquekeys.validate_many_champion_rotation_query, uniquekeys.convert_region_to_platform, ) def get_many_champion_rotation( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ChampionRotationData, None, None]: return self._get_many( ChampionRotationData, query, uniquekeys.for_many_champion_rotation_query, context, ) @put.register(ChampionRotationData) def put_champion_rotation( self, item: ChampionRotationData, context: PipelineContext = None ) -> None: self._put( ChampionRotationData, item, uniquekeys.for_champion_rotation, context=context, ) @put_many.register(ChampionRotationData) def put_many_champion_rotation( self, items: Iterable[ChampionRotationData], context: PipelineContext = None ) -> None: self._put_many( ChampionRotationData, items, uniquekeys.for_many_champion_rotation, context=context, ) ######################## # Champion Mastery API # ######################## # Champion Mastery @get.register(ChampionMastery) @validate_query( uniquekeys.validate_champion_mastery_query, uniquekeys.convert_region_to_platform, ) def get_champion_mastery( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ChampionMastery: return self._get( ChampionMastery, query, uniquekeys.for_champion_mastery_query, context ) @get_many.register(ChampionMastery) @validate_query( uniquekeys.validate_many_champion_mastery_query, uniquekeys.convert_region_to_platform, ) def get_many_champion_mastery( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ChampionMastery, None, None]: return self._get_many( ChampionMastery, query, uniquekeys.for_many_champion_mastery_query, context ) @put.register(ChampionMastery) def put_champion_mastery( self, item: ChampionMastery, context: PipelineContext = None ) -> None: self._put( ChampionMastery, item, uniquekeys.for_champion_mastery, context=context ) @put_many.register(ChampionMastery) def put_many_champion_mastery( self, items: Iterable[ChampionMastery], context: PipelineContext = None ) -> None: self._put_many( ChampionMastery, items, uniquekeys.for_many_champion_mastery, context=context, ) @get.register(ChampionMasteryData) @validate_query( uniquekeys.validate_champion_mastery_query, uniquekeys.convert_region_to_platform, ) def get_champion_mastery_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ChampionMasteryData: result = self.get_champion_mastery(query=query, context=context) if result._data[ChampionMasteryData] is not None and result._Ghost__is_loaded( ChampionMasteryData ): return result._data[ChampionMasteryData] else: raise NotFoundError # Champion Masteries @get.register(ChampionMasteries) @validate_query( uniquekeys.validate_champion_masteries_query, uniquekeys.convert_region_to_platform, ) def get_champion_masteries( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ChampionMasteries: return self._get( ChampionMasteries, query, uniquekeys.for_champion_masteries_query, context ) @get_many.register(ChampionMasteries) @validate_query( uniquekeys.validate_many_champion_masteries_query, uniquekeys.convert_region_to_platform, ) def get_many_champion_masteries( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ChampionMasteries, None, None]: return self._get_many( ChampionMasteries, query, uniquekeys.for_many_champion_masteries_query, context, ) @put.register(ChampionMasteries) def put_champion_masteries( self, item: ChampionMasteries, context: PipelineContext = None ) -> None: self._put( ChampionMasteries, item, uniquekeys.for_champion_masteries, context=context ) for cm in item: self._put( ChampionMastery, cm, uniquekeys.for_champion_mastery, context=context ) @put_many.register(ChampionMasteries) def put_many_champion_masteries( self, items: Iterable[ChampionMasteries], context: PipelineContext = None ) -> None: self._put_many( ChampionMasteries, items, uniquekeys.for_champion_masteries, context=context ) ############## # League API # ############## # LeagueSummonerEntries @get.register(LeagueSummonerEntries) @validate_query( uniquekeys.validate_league_entries_query, uniquekeys.convert_region_to_platform ) def get_league_summoner_entries( self, query: Mapping[str, Any], context: PipelineContext = None ) -> LeagueSummonerEntries: return self._get( LeagueSummonerEntries, query, uniquekeys.for_league_summoner_entries_query, context, ) @get_many.register(LeagueSummonerEntries) @validate_query( uniquekeys.validate_many_league_entries_query, uniquekeys.convert_region_to_platform, ) def get_many_league_summoner_entries( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[LeagueSummonerEntries, None, None]: return self._get_many( LeagueSummonerEntries, query, uniquekeys.for_many_league_summoner_entries_query, context, ) @put.register(LeagueSummonerEntries) def put_league_summoner_entries( self, item: LeagueSummonerEntries, context: PipelineContext = None ) -> None: self._put( LeagueSummonerEntries, item, uniquekeys.for_league_summoner_entries, context=context, ) @put_many.register(LeagueSummonerEntries) def put_many_league_summoner_entries( self, items: Iterable[LeagueSummonerEntries], context: PipelineContext = None ) -> None: self._put_many( LeagueSummonerEntries, items, uniquekeys.for_league_summoner_entries, context=context, ) # Challenger @get.register(ChallengerLeague) @validate_query( uniquekeys.validate_challenger_league_query, uniquekeys.convert_region_to_platform, ) def get_league_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ChallengerLeague: return self._get( ChallengerLeague, query, uniquekeys.for_challenger_league_query, context ) @get_many.register(ChallengerLeague) @validate_query( uniquekeys.validate_many_challenger_league_query, uniquekeys.convert_region_to_platform, ) def get_many_league_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ChallengerLeague, None, None]: return self._get_many( ChallengerLeague, query, uniquekeys.for_many_challenger_league_query, context, ) @put.register(ChallengerLeague) def put_league_summoner( self, item: ChallengerLeague, context: PipelineContext = None ) -> None: self._put( ChallengerLeague, item, uniquekeys.for_challenger_league, context=context ) @put_many.register(ChallengerLeague) def put_many_league_summoner( self, items: Iterable[ChallengerLeague], context: PipelineContext = None ) -> None: self._put_many( ChallengerLeague, items, uniquekeys.for_challenger_league, context=context ) # Grandmaster @get.register(GrandmasterLeague) @validate_query( uniquekeys.validate_grandmaster_league_query, uniquekeys.convert_region_to_platform, ) def get_league_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> GrandmasterLeague: return self._get( GrandmasterLeague, query, uniquekeys.for_grandmaster_league_query, context ) @get_many.register(GrandmasterLeague) @validate_query( uniquekeys.validate_many_grandmaster_league_query, uniquekeys.convert_region_to_platform, ) def get_many_league_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[GrandmasterLeague, None, None]: return self._get_many( GrandmasterLeague, query, uniquekeys.for_many_grandmaster_league_query, context, ) @put.register(GrandmasterLeague) def put_league_summoner( self, item: GrandmasterLeague, context: PipelineContext = None ) -> None: self._put( GrandmasterLeague, item, uniquekeys.for_grandmaster_league, context=context ) @put_many.register(GrandmasterLeague) def put_many_league_summoner( self, items: Iterable[GrandmasterLeague], context: PipelineContext = None ) -> None: self._put_many( GrandmasterLeague, items, uniquekeys.for_grandmaster_league, context=context ) # Master @get.register(MasterLeague) @validate_query( uniquekeys.validate_master_league_query, uniquekeys.convert_region_to_platform ) def get_league_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> MasterLeague: return self._get( MasterLeague, query, uniquekeys.for_master_league_query, context ) @get_many.register(MasterLeague) @validate_query( uniquekeys.validate_many_master_league_query, uniquekeys.convert_region_to_platform, ) def get_many_league_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[MasterLeague, None, None]: return self._get_many( MasterLeague, query, uniquekeys.for_many_master_league_query, context ) @put.register(MasterLeague) def put_league_summoner( self, item: MasterLeague, context: PipelineContext = None ) -> None: self._put(MasterLeague, item, uniquekeys.for_master_league, context=context) @put_many.register(MasterLeague) def put_many_league_summoner( self, items: Iterable[MasterLeague], context: PipelineContext = None ) -> None: self._put_many( MasterLeague, items, uniquekeys.for_master_league, context=context ) ################### # Static Data API # ################### # Champion @get.register(Champion) @validate_query( uniquekeys.validate_champion_query, uniquekeys.convert_region_to_platform ) def get_champion( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Champion: return self._get(Champion, query, uniquekeys.for_champion_query, context) @get_many.register(Champion) @validate_query( uniquekeys.validate_many_champion_query, uniquekeys.convert_region_to_platform ) def get_many_champion( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Champion, None, None]: return self._get_many( Champion, query, uniquekeys.for_many_champion_query, context ) @put.register(Champion) def put_champion(self, item: Champion, context: PipelineContext = None) -> None: self._put(Champion, item, uniquekeys.for_champion, context=context) @put_many.register(Champion) def put_many_champion( self, items: Iterable[Champion], context: PipelineContext = None ) -> None: self._put_many(Champion, items, uniquekeys.for_champion, context=context) @get.register(ChampionData) @validate_query( uniquekeys.validate_champion_query, uniquekeys.convert_region_to_platform ) def get_champion_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ChampionData: result = self.get_champion(query=query, context=context) if result._data[ChampionData] is not None and result._Ghost__is_loaded( ChampionData ): return result._data[ChampionData] else: raise NotFoundError # Champions @get.register(Champions) @validate_query( uniquekeys.validate_champions_query, uniquekeys.convert_region_to_platform ) def get_champions( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Champions: return self._get(Champions, query, uniquekeys.for_champions_query, context) @get_many.register(Champions) @validate_query( uniquekeys.validate_many_champions_query, uniquekeys.convert_region_to_platform ) def get_many_champions( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Champions, None, None]: return self._get_many( Champions, query, uniquekeys.for_many_champions_query, context ) @put.register(Champions) def put_champions( self, champions: Champions, context: PipelineContext = None ) -> None: self._put(Champions, champions, uniquekeys.for_champions, context=context) for champion in champions: self._put(Champion, champion, uniquekeys.for_champion, context=context) @put_many.register(Champions) def put_many_champions( self, champions: Iterable[Champions], context: PipelineContext = None ) -> None: self._put_many(Champions, champions, uniquekeys.for_champions, context=context) # Item @get.register(Item) @validate_query( uniquekeys.validate_item_query, uniquekeys.convert_region_to_platform ) def get_item( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Item: return self._get(Item, query, uniquekeys.for_item_query, context) @get_many.register(Item) @validate_query( uniquekeys.validate_many_item_query, uniquekeys.convert_region_to_platform ) def get_many_item( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Item, None, None]: return self._get_many(Item, query, uniquekeys.for_many_item_query, context) @put.register(Item) def put_item(self, item: Item, context: PipelineContext = None) -> None: self._put(Item, item, uniquekeys.for_item, context=context) @put_many.register(Item) def put_many_item( self, items: Iterable[Item], context: PipelineContext = None ) -> None: self._put_many(Item, items, uniquekeys.for_item, context=context) @get.register(ItemData) @validate_query( uniquekeys.validate_item_query, uniquekeys.convert_region_to_platform ) def get_item_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ItemData: result = self.get_item(query=query, context=context) if result._data[ItemData] is not None and result._Ghost__is_loaded(ItemData): return result._data[ItemData] else: raise NotFoundError # Items @get.register(Items) @validate_query( uniquekeys.validate_items_query, uniquekeys.convert_region_to_platform ) def get_items( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Items: return self._get(Items, query, uniquekeys.for_items_query, context=context) @get_many.register(Items) @validate_query( uniquekeys.validate_many_items_query, uniquekeys.convert_region_to_platform ) def get_many_items( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Items, None, None]: return self._get_many(Items, query, uniquekeys.for_many_items_query, context) @put.register(Items) def put_items(self, items: Items, context: PipelineContext = None) -> None: self._put(Items, items, uniquekeys.for_items, context=context) for item in items: self._put(Item, item, uniquekeys.for_item, context=context) @put_many.register(Items) def put_many_items( self, many_items: Iterable[Items], context: PipelineContext = None ) -> None: self._put_many(Items, many_items, uniquekeys.for_items, context=context) # Language @get.register(Locales) @validate_query( uniquekeys.validate_languages_query, uniquekeys.convert_region_to_platform ) def get_languages( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Locales: return self._get(Locales, query, uniquekeys.for_languages_query, context) @get_many.register(Locales) @validate_query( uniquekeys.validate_many_languages_query, uniquekeys.convert_region_to_platform ) def get_many_languages( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Locales, None, None]: return self._get_many( Locales, query, uniquekeys.for_many_languages_query, context ) @put.register(Locales) def put_languages(self, item: Locales, context: PipelineContext = None) -> None: self._put(Locales, item, uniquekeys.for_languages, context=context) @put_many.register(Locales) def put_many_languages( self, items: Iterable[Locales], context: PipelineContext = None ) -> None: self._put_many(Locales, items, uniquekeys.for_languages, context=context) # Language strings @get.register(LanguageStrings) @validate_query( uniquekeys.validate_language_strings_query, uniquekeys.convert_region_to_platform, ) def get_language_strings( self, query: Mapping[str, Any], context: PipelineContext = None ) -> LanguageStrings: return self._get( LanguageStrings, query, uniquekeys.for_language_strings_query, context ) @get_many.register(LanguageStrings) @validate_query( uniquekeys.validate_many_language_strings_query, uniquekeys.convert_region_to_platform, ) def get_many_language_strings( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[LanguageStrings, None, None]: return self._get_many( LanguageStrings, query, uniquekeys.for_many_language_strings_query, context ) @put.register(LanguageStrings) def put_language_strings( self, item: LanguageStrings, context: PipelineContext = None ) -> None: self._put( LanguageStrings, item, uniquekeys.for_language_strings, context=context ) @put_many.register(LanguageStrings) def put_many_language_strings( self, items: Iterable[LanguageStrings], context: PipelineContext = None ) -> None: self._put_many( LanguageStrings, items, uniquekeys.for_language_strings, context=context ) @get.register(LanguageStringsData) @validate_query( uniquekeys.validate_language_strings_query, uniquekeys.convert_region_to_platform, ) def get_language_strings_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> LanguageStringsData: result = self.get_language_strings(query=query, context=context) if result._data[LanguageStringsData] is not None and result._Ghost__is_loaded( LanguageStringsData ): return result._data[LanguageStringsData] else: raise NotFoundError # Map @get.register(Map) @validate_query( uniquekeys.validate_map_query, uniquekeys.convert_region_to_platform ) def get_map(self, query: Mapping[str, Any], context: PipelineContext = None) -> Map: return self._get(Map, query, uniquekeys.for_map_query, context) @get_many.register(Map) @validate_query( uniquekeys.validate_many_map_query, uniquekeys.convert_region_to_platform ) def get_many_map( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Map, None, None]: return self._get_many(Map, query, uniquekeys.for_many_map_query, context) @put.register(Map) def put_map(self, item: Map, context: PipelineContext = None) -> None: self._put(Map, item, uniquekeys.for_map, context=context) @put_many.register(Map) def put_many_map( self, items: Iterable[Map], context: PipelineContext = None ) -> None: self._put_many(Map, items, uniquekeys.for_map, context=context) @get.register(MapData) @validate_query( uniquekeys.validate_map_query, uniquekeys.convert_region_to_platform ) def get_map_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> MapData: result = self.get_map(query=query, context=context) if result._data[MapData] is not None and result._Ghost__is_loaded(MapData): return result._data[MapData] else: raise NotFoundError # Maps @get.register(Maps) @validate_query( uniquekeys.validate_maps_query, uniquekeys.convert_region_to_platform ) def get_maps( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Maps: return self._get(Maps, query, uniquekeys.for_maps_query, context) @get_many.register(Maps) @validate_query( uniquekeys.validate_many_maps_query, uniquekeys.convert_region_to_platform ) def get_many_maps( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Maps, None, None]: return self._get_many(Maps, query, uniquekeys.for_many_maps_query, context) @put.register(Maps) def put_maps(self, item: Maps, context: PipelineContext = None) -> None: self._put(Maps, item, uniquekeys.for_maps, context=context) for map in item: self._put(Map, map, uniquekeys.for_map, context=context) @put_many.register(Maps) def put_many_maps( self, items: Iterable[Maps], context: PipelineContext = None ) -> None: self._put_many(Maps, items, uniquekeys.for_maps, context=context) # Profile Icon @get.register(ProfileIcon) @validate_query( uniquekeys.validate_profile_icon_query, uniquekeys.convert_region_to_platform ) def get_profile_icon( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ProfileIcon: return self._get(ProfileIcon, query, uniquekeys.for_profile_icon_query, context) @get_many.register(ProfileIcon) @validate_query( uniquekeys.validate_many_profile_icon_query, uniquekeys.convert_region_to_platform, ) def get_many_profile_icon( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ProfileIcon, None, None]: return self._get_many( ProfileIcon, query, uniquekeys.for_many_profile_icon_query, context ) @put.register(ProfileIcon) def put_profile_icon( self, item: ProfileIcon, context: PipelineContext = None ) -> None: self._put(ProfileIcon, item, uniquekeys.for_profile_icon, context=context) @put_many.register(ProfileIcon) def put_many_profile_icon( self, items: Iterable[ProfileIcon], context: PipelineContext = None ) -> None: self._put_many(ProfileIcon, items, uniquekeys.for_profile_icon, context=context) @get.register(ProfileIconData) @validate_query( uniquekeys.validate_profile_icon_query, uniquekeys.convert_region_to_platform ) def get_profile_icon_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ProfileIconData: result = self.get_profile_icon(query=query, context=context) if result._data[ProfileIconData] is not None and result._Ghost__is_loaded( ProfileIconData ): return result._data[ProfileIconData] else: raise NotFoundError # Profile Icons @get.register(ProfileIcons) @validate_query( uniquekeys.validate_profile_icons_query, uniquekeys.convert_region_to_platform ) def get_profile_icons( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ProfileIcons: return self._get( ProfileIcons, query, uniquekeys.for_profile_icons_query, context ) @get_many.register(ProfileIcons) @validate_query( uniquekeys.validate_many_profile_icons_query, uniquekeys.convert_region_to_platform, ) def get_many_profile_icons( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ProfileIcons, None, None]: return self._get_many( ProfileIcons, query, uniquekeys.for_many_profile_icons_query, context ) @put.register(ProfileIcons) def put_profile_icons( self, item: ProfileIcons, context: PipelineContext = None ) -> None: self._put(ProfileIcons, item, uniquekeys.for_profile_icons, context=context) for profile_icon in item: self._put( ProfileIcon, profile_icon, uniquekeys.for_profile_icon, context=context ) @put_many.register(ProfileIcons) def put_many_profile_icons( self, items: Iterable[ProfileIcons], context: PipelineContext = None ) -> None: self._put_many( ProfileIcons, items, uniquekeys.for_profile_icons, context=context ) # Realm @get.register(Realms) @validate_query( uniquekeys.validate_realms_query, uniquekeys.convert_region_to_platform ) def get_realms( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Realms: return self._get(Realms, query, uniquekeys.for_realms_query, context) @get_many.register(Realms) @validate_query( uniquekeys.validate_many_realms_query, uniquekeys.convert_region_to_platform ) def get_many_realms( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Realms, None, None]: return self._get_many(Realms, query, uniquekeys.for_many_realms_query, context) @put.register(Realms) def put_realms(self, item: Realms, context: PipelineContext = None) -> None: self._put(Realms, item, uniquekeys.for_realms, context=context) @put_many.register(Realms) def put_many_realms( self, items: Iterable[Realms], context: PipelineContext = None ) -> None: self._put_many(Realms, items, uniquekeys.for_realms, context=context) @get.register(RealmData) @validate_query( uniquekeys.validate_realms_query, uniquekeys.convert_region_to_platform ) def get_realms_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> RealmData: result = self.get_realms(query=query, context=context) if result._data[RealmData] is not None and result._Ghost__is_loaded(RealmData): return result._data[RealmData] else: raise NotFoundError # Rune @get.register(Rune) @validate_query( uniquekeys.validate_rune_query, uniquekeys.convert_region_to_platform ) def get_rune( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Rune: return self._get(Rune, query, uniquekeys.for_rune_query, context) @get_many.register(Rune) @validate_query( uniquekeys.validate_many_rune_query, uniquekeys.convert_region_to_platform ) def get_many_rune( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Rune, None, None]: return self._get_many(Rune, query, uniquekeys.for_many_rune_query, context) @put.register(Rune) def put_rune(self, item: Rune, context: PipelineContext = None) -> None: self._put(Rune, item, uniquekeys.for_rune, context=context) @put_many.register(Rune) def put_many_rune( self, items: Iterable[Rune], context: PipelineContext = None ) -> None: self._put_many(Rune, items, uniquekeys.for_rune, context=context) @get.register(RuneData) @validate_query( uniquekeys.validate_rune_query, uniquekeys.convert_region_to_platform ) def get_rune_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> RuneData: result = self.get_rune(query=query, context=context) if result._data[RuneData] is not None and result._Ghost__is_loaded(RuneData): return result._data[RuneData] else: raise NotFoundError # Runes @get.register(Runes) @validate_query( uniquekeys.validate_runes_query, uniquekeys.convert_region_to_platform ) def get_runes( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Runes: return self._get(Runes, query, uniquekeys.for_runes_query, context) @get_many.register(Runes) @validate_query( uniquekeys.validate_many_runes_query, uniquekeys.convert_region_to_platform ) def get_many_runes( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Runes, None, None]: return self._get_many(Runes, query, uniquekeys.for_many_runes_query, context) @put.register(Runes) def put_runes(self, item: Runes, context: PipelineContext = None) -> None: self._put(Runes, item, uniquekeys.for_runes, context=context) for rune in item: self._put(Rune, rune, uniquekeys.for_rune, context=context) @put_many.register(Runes) def put_many_runes( self, items: Iterable[Runes], context: PipelineContext = None ) -> None: self._put_many(Runes, items, uniquekeys.for_runes, context=context) # Summoner Spell @get.register(SummonerSpell) @validate_query( uniquekeys.validate_summoner_spell_query, uniquekeys.convert_region_to_platform ) def get_summoner_spell( self, query: Mapping[str, Any], context: PipelineContext = None ) -> SummonerSpell: return self._get( SummonerSpell, query, uniquekeys.for_summoner_spell_query, context ) @get_many.register(SummonerSpell) @validate_query( uniquekeys.validate_many_summoner_spell_query, uniquekeys.convert_region_to_platform, ) def get_many_summoner_spell( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[SummonerSpell, None, None]: return self._get_many( SummonerSpell, query, uniquekeys.for_many_summoner_spell_query, context ) @put.register(SummonerSpell) def put_summoner_spell( self, item: SummonerSpell, context: PipelineContext = None ) -> None: self._put(SummonerSpell, item, uniquekeys.for_summoner_spell, context=context) @put_many.register(SummonerSpell) def put_many_summoner_spell( self, items: Iterable[SummonerSpell], context: PipelineContext = None ) -> None: self._put_many( SummonerSpell, items, uniquekeys.for_summoner_spell, context=context ) @get.register(SummonerSpellData) @validate_query( uniquekeys.validate_summoner_spell_query, uniquekeys.convert_region_to_platform ) def get_summoner_spell_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> SummonerSpellData: result = self.get_summoner_spell(query=query, context=context) if result._data[SummonerSpellData] is not None and result._Ghost__is_loaded( SummonerSpellData ): return result._data[SummonerSpellData] else: raise NotFoundError # Summoner Spells @get.register(SummonerSpells) @validate_query( uniquekeys.validate_summoner_spells_query, uniquekeys.convert_region_to_platform ) def get_summoner_spells( self, query: Mapping[str, Any], context: PipelineContext = None ) -> SummonerSpells: return self._get( SummonerSpells, query, uniquekeys.for_summoner_spells_query, context ) @get_many.register(SummonerSpells) @validate_query( uniquekeys.validate_many_summoner_spells_query, uniquekeys.convert_region_to_platform, ) def get_many_summoner_spells( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[SummonerSpells, None, None]: return self._get_many( SummonerSpells, query, uniquekeys.for_many_summoner_spells_query, context ) @put.register(SummonerSpells) def put_summoner_spells( self, item: SummonerSpells, context: PipelineContext = None ) -> None: self._put(SummonerSpells, item, uniquekeys.for_summoner_spells, context=context) for summoner_spell in item: self._put( SummonerSpell, summoner_spell, uniquekeys.for_summoner_spell, context=context, ) @put_many.register(SummonerSpells) def put_many_summoner_spells( self, items: Iterable[SummonerSpells], context: PipelineContext = None ) -> None: self._put_many( SummonerSpells, items, uniquekeys.for_summoner_spells, context=context ) # Versions @get.register(Versions) @validate_query( uniquekeys.validate_versions_query, uniquekeys.convert_region_to_platform ) def get_versions( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Versions: return self._get( Versions, query, uniquekeys.for_versions_query, context=context ) @get_many.register(Versions) @validate_query( uniquekeys.validate_many_versions_query, uniquekeys.convert_region_to_platform ) def get_many_versions( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Versions, None, None]: return self._get_many( Versions, query, uniquekeys.for_many_versions_query, context=context ) @put.register(Versions) def put_versions(self, item: Versions, context: PipelineContext = None) -> None: self._put(Versions, item, uniquekeys.for_versions, context=context) @put_many.register(Versions) def put_many_versions( self, items: Iterable[Versions], context: PipelineContext = None ) -> None: self._put_many(Versions, items, uniquekeys.for_versions, context=context) ############## # Status API # ############## @get.register(ShardStatus) @validate_query( uniquekeys.validate_shard_status_query, uniquekeys.convert_region_to_platform ) def get_shard_status( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ShardStatus: return self._get(ShardStatus, query, uniquekeys.for_shard_status_query, context) @get_many.register(ShardStatus) @validate_query( uniquekeys.validate_many_shard_status_query, uniquekeys.convert_region_to_platform, ) def get_many_shard_status( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[ShardStatus, None, None]: return self._get_many( ShardStatus, query, uniquekeys.for_many_shard_status_query, context ) @put.register(ShardStatus) def put_shard_status( self, item: ShardStatus, context: PipelineContext = None ) -> None: self._put(ShardStatus, item, uniquekeys.for_shard_status, context=context) @put_many.register(ShardStatus) def put_many_shard_status( self, items: Iterable[ShardStatus], context: PipelineContext = None ) -> None: self._put_many(ShardStatus, items, uniquekeys.for_shard_status, context=context) @get.register(ShardStatusData) @validate_query( uniquekeys.validate_shard_status_query, uniquekeys.convert_region_to_platform ) def get_shard_status_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> ShardStatusData: result = self.get_shard_status(query=query, context=context) if result._data[ShardStatusData] is not None and result._Ghost__is_loaded( ShardStatusData ): return result._data[ShardStatusData] else: raise NotFoundError ############# # Match API # ############# @get.register(Match) @validate_query(uniquekeys.validate_match_query, uniquekeys.convert_region_to_platform) def get_match( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Match: return self._get(Match, query, uniquekeys.for_match_query, context) @get_many.register(Match) @validate_query(uniquekeys.validate_many_match_query, uniquekeys.convert_region_to_platform) def get_many_match( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Match, None, None]: return self._get_many(Match, query, uniquekeys.for_many_match_query, context) @put.register(Match) def put_match(self, item: Match, context: PipelineContext = None) -> None: self._put(Match, item, uniquekeys.for_match, context=context) @put_many.register(Match) def put_many_match( self, items: Iterable[Match], context: PipelineContext = None ) -> None: self._put_many(Match, items, uniquekeys.for_match, context=context) @get.register(MatchData) @validate_query(uniquekeys.validate_match_query, uniquekeys.convert_region_to_platform) def get_match_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> MatchData: result = self.get_match(query=query, context=context) if result._data[MatchData] is not None and result._Ghost__is_loaded(MatchData): return result._data[MatchData] else: raise NotFoundError # Timeline @get.register(Timeline) @validate_query( uniquekeys.validate_match_timeline_query, uniquekeys.convert_region_to_platform ) def get_match_timeline( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Timeline: return self._get(Timeline, query, uniquekeys.for_match_timeline_query, context) @get_many.register(Timeline) @validate_query( uniquekeys.validate_many_match_timeline_query, uniquekeys.convert_region_to_platform ) def get_many_match_timeline( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Timeline, None, None]: return self._get_many( Timeline, query, uniquekeys.for_many_match_timeline_query, context ) @put.register(Timeline) def put_match_timeline( self, item: Timeline, context: PipelineContext = None ) -> None: self._put(Timeline, item, uniquekeys.for_match_timeline, context=context) @put_many.register(Timeline) def put_many_match_timeline( self, items: Iterable[Timeline], context: PipelineContext = None ) -> None: self._put_many(Timeline, items, uniquekeys.for_match_timeline, context=context) @get.register(TimelineData) @validate_query( uniquekeys.validate_match_timeline_query, uniquekeys.convert_region_to_platform ) def get_match_timeline_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> TimelineData: result = self.get_match_timeline(query=query, context=context) if result._data[TimelineData] is not None and result._Ghost__is_loaded( TimelineData ): return result._data[TimelineData] else: raise NotFoundError ################# # Spectator API # ################# # Current Match @get.register(CurrentMatch) @validate_query( uniquekeys.validate_current_match_query, uniquekeys.convert_region_to_platform ) def get_current_match( self, query: Mapping[str, Any], context: PipelineContext = None ) -> CurrentMatch: return self._get( CurrentMatch, query, uniquekeys.for_current_match_query, context ) @get_many.register(CurrentMatch) @validate_query( uniquekeys.validate_many_current_match_query, uniquekeys.convert_region_to_platform, ) def get_many_current_match( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[CurrentMatch, None, None]: return self._get_many( CurrentMatch, query, uniquekeys.for_many_current_match_query, context ) @put.register(CurrentMatch) def put_current_match( self, item: CurrentMatch, context: PipelineContext = None ) -> None: self._put(CurrentMatch, item, uniquekeys.for_current_match, context=context) @put_many.register(CurrentMatch) def put_many_current_match( self, items: Iterable[CurrentMatch], context: PipelineContext = None ) -> None: self._put_many( CurrentMatch, items, uniquekeys.for_current_match, context=context ) @get.register(CurrentGameInfoData) @validate_query( uniquekeys.validate_current_match_query, uniquekeys.convert_region_to_platform ) def get_current_match_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> CurrentGameInfoData: result = self.get_current_match(query=query, context=context) if result._data[CurrentGameInfoData] is not None and result._Ghost__is_loaded( CurrentGameInfoData ): return result._data[CurrentGameInfoData] else: raise NotFoundError # Featured Matches @get.register(FeaturedMatches) @validate_query( uniquekeys.validate_featured_matches_query, uniquekeys.convert_region_to_platform, ) def get_featured_matches( self, query: Mapping[str, Any], context: PipelineContext = None ) -> FeaturedMatches: return self._get( FeaturedMatches, query, uniquekeys.for_featured_matches_query, context ) @get_many.register(FeaturedMatches) @validate_query( uniquekeys.validate_many_featured_matches_query, uniquekeys.convert_region_to_platform, ) def get_many_featured_matches( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[FeaturedMatches, None, None]: return self._get_many( FeaturedMatches, query, uniquekeys.for_many_featured_matches_query, context ) @put.register(FeaturedMatches) def put_featured_matches( self, item: FeaturedMatches, context: PipelineContext = None ) -> None: self._put( FeaturedMatches, item, uniquekeys.for_featured_matches, context=context ) @put_many.register(FeaturedMatches) def put_many_featured_matches( self, items: Iterable[FeaturedMatches], context: PipelineContext = None ) -> None: self._put_many( FeaturedMatches, items, uniquekeys.for_featured_matches, context=context ) ################ # Summoner API # ################ @get.register(Summoner) @validate_query( uniquekeys.validate_summoner_query, uniquekeys.convert_region_to_platform ) def get_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Summoner: return self._get(Summoner, query, uniquekeys.for_summoner_query, context) @get_many.register(Summoner) @validate_query( uniquekeys.validate_many_summoner_query, uniquekeys.convert_region_to_platform ) def get_many_summoner( self, query: Mapping[str, Any], context: PipelineContext = None ) -> Generator[Summoner, None, None]: return self._get_many( Summoner, query, uniquekeys.for_many_summoner_query, context ) @put.register(Summoner) def put_summoner(self, item: Summoner, context: PipelineContext = None) -> None: self._put(Summoner, item, uniquekeys.for_summoner, context=context) @put_many.register(Summoner) def put_many_summoner( self, items: Iterable[Summoner], context: PipelineContext = None ) -> None: self._put_many(Summoner, items, uniquekeys.for_summoner, context=context) @get.register(SummonerData) @validate_query( uniquekeys.validate_summoner_query, uniquekeys.convert_region_to_platform ) def get_summoner_data( self, query: Mapping[str, Any], context: PipelineContext = None ) -> SummonerData: result = self.get_summoner(query=query, context=context) if result._data[SummonerData] is not None and result._Ghost__is_loaded( SummonerData ): return result._data[SummonerData] else: raise NotFoundError
mit
55161022443c5dfbb5e9f70dc14567ef
33.730065
96
0.64473
3.672218
false
false
false
false
meraki-analytics/cassiopeia
setup.py
1
1494
#!/usr/bin/env python import sys from setuptools import setup, find_packages install_requires = [ "datapipelines>=1.0.7", "merakicommons>=1.0.10", "Pillow", "arrow", "requests", ] # Require python 3.6 if sys.version_info.major != 3 and sys.version_info.minor != 6: sys.exit("Cassiopeia requires Python 3.6.") setup( name="cassiopeia", version="5.0.3", # Keep the Cass version at parity with the largest Riot API major version, use the minor version for breaking changes, and the patch version for everything else author="Jason Maldonis; Rob Rua", author_email="team@merakianalytics.com", url="https://github.com/meraki-analytics/cassiopeia", description="Riot Games Developer API Wrapper (3rd Party)", keywords=["LoL", "League of Legends", "Riot Games", "API", "REST"], classifiers=[ "Development Status :: 4 - Beta", "Programming Language :: Python :: 3", "Environment :: Web Environment", "Operating System :: OS Independent", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Games/Entertainment", "Topic :: Games/Entertainment :: Real Time Strategy", "Topic :: Games/Entertainment :: Role-Playing", "Topic :: Software Development :: Libraries :: Python Modules", ], license="MIT", packages=find_packages(), zip_safe=True, install_requires=install_requires, include_package_data=True, )
mit
5ed0a17d2eb0ee7e592f67d2003cdd9b
32.2
182
0.649264
3.670762
false
false
false
false
meraki-analytics/cassiopeia
cassiopeia/datastores/kernel/championmastery.py
1
8321
from typing import Type, TypeVar, MutableMapping, Any, Iterable, Generator from datapipelines import ( DataSource, PipelineContext, Query, NotFoundError, validate_query, ) from .common import KernelSource, APINotFoundError from ...data import Platform from ...dto.championmastery import ( ChampionMasteryDto, ChampionMasteryListDto, ChampionMasteryScoreDto, ) from ..uniquekeys import convert_region_to_platform T = TypeVar("T") class ChampionMasteryAPI(KernelSource): @DataSource.dispatch def get( self, type: Type[T], query: MutableMapping[str, Any], context: PipelineContext = None, ) -> T: pass @DataSource.dispatch def get_many( self, type: Type[T], query: MutableMapping[str, Any], context: PipelineContext = None, ) -> Iterable[T]: pass _validate_get_champion_mastery_query = ( Query.has("platform") .as_(Platform) .also.has("summoner.id") .as_(str) .also.has("champion.id") .as_(int) ) @get.register(ChampionMasteryDto) @validate_query(_validate_get_champion_mastery_query, convert_region_to_platform) def get_champion_mastery( self, query: MutableMapping[str, Any], context: PipelineContext = None ) -> ChampionMasteryDto: parameters = {"platform": query["platform"].value} endpoint = "lol/champion-mastery/v4/champion-masteries/by-summoner/{summonerId}/by-champion/{championId}".format( summonerId=query["summoner.id"], championId=query["champion.id"] ) try: data = self._get(endpoint=endpoint, parameters=parameters) except APINotFoundError as error: raise NotFoundError(str(error)) from error data["region"] = query["platform"].region.value data["summonerId"] = query["summoner.id"] return ChampionMasteryDto(data) _validate_get_many_champion_mastery_query = ( Query.has("platform") .as_(Platform) .also.has("summonerId") .as_(str) .also.has("championIds") .as_(Iterable) ) @get_many.register(ChampionMasteryDto) @validate_query( _validate_get_many_champion_mastery_query, convert_region_to_platform ) def get_many_champion_mastery( self, query: MutableMapping[str, Any], context: PipelineContext = None ) -> Generator[ChampionMasteryDto, None, None]: parameters = {"platform": query["platform"].value} endpoint = "lol/champion-mastery/v4/champion-masteries/by-summoner/{summonerId}".format( summonerId=query["summonerId"] ) try: data = self._get(endpoint=endpoint, parameters=parameters) except APINotFoundError as error: raise NotFoundError(str(error)) from error masteries = {mastery["championId"]: mastery for mastery in data} def generator(): for id in query["championIds"]: try: mastery = masteries[id] except KeyError as error: raise NotFoundError( 'Summoner has no mastery on champion with id "{id}"'.format( id=id ) ) from error mastery["summonerId"] = query["summonerId"] mastery["region"] = query["platform"].region.value yield ChampionMasteryDto(mastery) return generator() _validate_get_champion_mastery_list_query = ( Query.has("platform").as_(Platform).also.has("summoner.id").as_(str) ) @get.register(ChampionMasteryListDto) @validate_query( _validate_get_champion_mastery_list_query, convert_region_to_platform ) def get_champion_mastery_list( self, query: MutableMapping[str, Any], context: PipelineContext = None ) -> ChampionMasteryListDto: parameters = {"platform": query["platform"].value} endpoint = "lol/champion-mastery/v4/champion-masteries/by-summoner/{summonerId}".format( summonerId=query["summoner.id"] ) try: data = self._get(endpoint=endpoint, parameters=parameters) except APINotFoundError as error: raise NotFoundError(str(error)) from error for cm in data: cm["region"] = query["region"] return ChampionMasteryListDto( { "masteries": data, "summonerId": query["summoner.id"], "region": query["platform"].region.value, } ) _validate_get_many_champion_mastery_list_query = ( Query.has("platform").as_(Platform).also.has("summoner.ids").as_(Iterable) ) @get_many.register(ChampionMasteryListDto) @validate_query( _validate_get_many_champion_mastery_list_query, convert_region_to_platform ) def get_many_champion_mastery_list( self, query: MutableMapping[str, Any], context: PipelineContext = None ) -> Generator[ChampionMasteryListDto, None, None]: def generator(): parameters = {"platform": query["platform"].value} for summoner_id in query["summoner.ids"]: endpoint = "lol/champion-mastery/v4/champion-masteries/by-summoner/{summonerId}".format( summonerId=summoner_id ) try: data = self._get(endpoint=endpoint, parameters=parameters) except APINotFoundError as error: raise NotFoundError(str(error)) from error yield ChampionMasteryListDto( { "masteries": data, "summonerId": summoner_id, "region": query["platform"].region.value, } ) return generator() _validate_get_champion_mastery_score_query = ( Query.has("platform").as_(Platform).also.has("summoner.id").as_(str) ) @get.register(ChampionMasteryScoreDto) @validate_query( _validate_get_champion_mastery_score_query, convert_region_to_platform ) def get_champion_mastery_score( self, query: MutableMapping[str, Any], context: PipelineContext = None ) -> ChampionMasteryScoreDto: parameters = {"platform": query["platform"].value} endpoint = "lol/champion-mastery/v4/scores/by-summoner/{summonerId}".format( summonerId=query["summoner.id"] ) try: data = self._get(endpoint=endpoint, parameters=parameters) except APINotFoundError as error: raise NotFoundError(str(error)) from error return ChampionMasteryScoreDto( { "region": query["platform"].region.value, "summonerId": query["summoner.id"], "score": data, } ) _validate_get_many_champion_mastery_score_query = ( Query.has("platform").as_(Platform).also.has("summoner.ids").as_(Iterable) ) @get_many.register(ChampionMasteryScoreDto) @validate_query( _validate_get_many_champion_mastery_score_query, convert_region_to_platform ) def get_many_champion_mastery_score( self, query: MutableMapping[str, Any], context: PipelineContext = None ) -> Generator[ChampionMasteryScoreDto, None, None]: def generator(): parameters = {"platform": query["platform"].value} for summoner_id in query["summoner.ids"]: endpoint = ( "lol/champion-mastery/v4/scores/by-summoner/{summonerId}".format( summonerId=summoner_id ) ) try: data = self._get(endpoint=endpoint, parameters=parameters) except APINotFoundError as error: raise NotFoundError(str(error)) from error yield ChampionMasteryScoreDto( { "region": query["platform"].region.value, "summonerId": summoner_id, "score": data, } ) return generator()
mit
a34de93abce5f48b8063de7c5c8fe750
34.559829
121
0.583343
3.775408
false
false
false
false
meraki-analytics/cassiopeia
cassiopeia/datastores/riotapi/__init__.py
1
3475
from typing import Iterable, Set, Dict import itertools import os from datapipelines import CompositeDataSource from .common import RiotAPIService, RiotAPIRateLimiter def _default_services( api_key: str, limiting_share: float = 1.0, request_error_handling: Dict = None ) -> Set[RiotAPIService]: from ..common import HTTPClient from ..image import ImageDataSource from .champion import ChampionAPI from .summoner import SummonerAPI from .championmastery import ChampionMasteryAPI from .match import MatchAPI from .spectator import SpectatorAPI from .status import StatusAPI from .leagues import LeaguesAPI from .thirdpartycode import ThirdPartyCodeAPI from ...data import Platform, Continent app_rate_limiter = { platform: RiotAPIRateLimiter(limiting_share=limiting_share) for platform in itertools.chain(Platform, Continent) } client = HTTPClient() services = { ImageDataSource(client), ChampionAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), SummonerAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), ChampionMasteryAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), MatchAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), SpectatorAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), StatusAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), LeaguesAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), ThirdPartyCodeAPI( api_key, app_rate_limiter=app_rate_limiter, request_error_handling=request_error_handling, http_client=client, ), } return services class RiotAPI(CompositeDataSource): def __init__( self, api_key: str = None, services: Iterable[RiotAPIService] = None, limiting_share: float = 1.0, request_error_handling: Dict = None, ) -> None: if api_key is None: api_key = "RIOT_API_KEY" # Use this env variable. if not api_key.startswith("RGAPI"): api_key = os.environ.get(api_key, None) if services is None: services = _default_services( api_key=api_key, limiting_share=limiting_share, request_error_handling=request_error_handling, ) super().__init__(services) def set_api_key(self, key: str): for sources in self._sources.values(): for source in sources: if isinstance(source, RiotAPIService): source._headers["X-Riot-Token"] = key
mit
2313cf11579bbeabd528068874a79bca
30.306306
82
0.592806
3.962372
false
false
false
false
meraki-analytics/cassiopeia
cassiopeia/core/championmastery.py
1
9150
import arrow from typing import Union from merakicommons.cache import lazy, lazy_property from merakicommons.container import searchable from ..data import Region, Platform from .common import ( CoreData, CassiopeiaObject, CassiopeiaGhost, CassiopeiaLazyList, CoreDataList, get_latest_version, ghost_load_on, ) from ..dto.championmastery import ChampionMasteryDto from .staticdata.champion import Champion from .summoner import Summoner from ..dto import championmastery as dto ############## # Data Types # ############## class ChampionMasteryListData(CoreDataList): _dto_type = dto.ChampionMasteryListDto _renamed = {} class ChampionMasteryData(CoreData): _dto_type = ChampionMasteryDto _renamed = { "championLevel": "level", "championPoints": "points", "playerId": "summonerId", "championPointsUntilNextLevel": "pointsUntilNextLevel", "championPointsSinceLastLevel": "pointsSinceLastLevel", "lastPlayTime": "lastPlayed", "tokensEarned": "tokens", } ############## # Core Types # ############## class ChampionMasteries(CassiopeiaLazyList): _data_types = {ChampionMasteryListData} def __init__(self, *, summoner: Summoner, region: Union[Region, str] = None): self.__summoner = summoner kwargs = {"region": region} CassiopeiaObject.__init__(self, **kwargs) @classmethod def __get_query_from_kwargs__( cls, *, summoner: Union[Summoner, int, str], region: Union[Region, str] ) -> dict: query = {"region": region} if isinstance(summoner, Summoner): query["summoner.id"] = summoner.id elif isinstance(summoner, str): if len(summoner) < 35: # It's a summoner name query["summoner.id"] = Summoner(name=summoner, region=region).id else: # It's probably a summoner id query["summoner.id"] = summoner return query @lazy_property def region(self) -> Region: return Region(self._data[ChampionMasteryListData].region) @lazy_property def platform(self) -> Platform: return self.region.platform @property def summoner(self): return self.__summoner @searchable( { str: ["champion", "summoner"], int: ["points", "level"], bool: ["chest_granted"], arrow.Arrow: ["last_played"], Champion: ["champion"], Summoner: ["summoner"], } ) class ChampionMastery(CassiopeiaGhost): _data_types = {ChampionMasteryData} def __init__( self, *, summoner: Union[Summoner, int, str] = None, champion: Union[Champion, int, str] = None, region: Union[Region, str] = None, _account_id: str = None ): kwargs = {"region": region} if _account_id is not None: summoner = Summoner(account_id=_account_id, region=region) if summoner is not None: if isinstance(summoner, Summoner): self.__class__.summoner.fget._lazy_set(self, summoner) elif isinstance(summoner, str): if len(summoner) < 35: # It's a summoner name summoner = Summoner(name=summoner, region=region) self.__class__.summoner.fget._lazy_set(self, summoner) else: # It's probably a summoner id kwargs["summonerId"] = summoner if champion is not None: if isinstance(champion, Champion): self.__class__.champion.fget._lazy_set(self, champion) elif isinstance(champion, str): champion = Champion( name=champion, region=self.region, version=get_latest_version(self.region, endpoint="champion"), ) self.__class__.champion.fget._lazy_set(self, champion) else: # int kwargs["championId"] = champion super().__init__(**kwargs) @classmethod def __get_query_from_kwargs__( cls, *, summoner: Union[Summoner, int, str], champion: Union[Champion, int, str], region: Union[Region, str] ) -> dict: query = {"region": region} if isinstance(summoner, Summoner): query["summoner.id"] = summoner.id elif isinstance(summoner, str): if len(summoner) < 35: # It's a summoner name query["summoner.id"] = Summoner(name=summoner, region=region).id else: # It's probably a summoner id query["summoner.id"] = summoner if isinstance(champion, Champion): query["champion.id"] = champion.id elif isinstance(champion, str): query["champion.id"] = Champion(name=champion, region=region).id else: # int query["champion.id"] = champion return query def __get_query__(self): return { "region": self.region, "platform": self.platform.value, "summoner.id": self.summoner.id, "champion.id": self.champion.id, } def __load__(self, load_group: CoreData = None) -> None: from datapipelines import NotFoundError try: return super().__load__(load_group) except NotFoundError: from ..transformers.championmastery import ChampionMasteryTransformer dto = { "championLevel": 0, "chestGranted": False, "championPoints": 0, "championPointsUntilNextLevel": 1800, "tokensEarned": 0, "championPointsSinceLastLevel": 0, "lastPlayTime": None, } data = ChampionMasteryTransformer.champion_mastery_dto_to_data(None, dto) self.__load_hook__(load_group, data) def __eq__(self, other: "ChampionMastery"): if not isinstance(other, ChampionMastery) or self.region != other.region: return False return self.champion == other.champion and self.summoner == other.summoner def __str__(self): return "ChampionMastery(summoner={summoner}, champion={champion})".format( summoner=str(self.summoner), champion=str(self.champion) ) __hash__ = CassiopeiaGhost.__hash__ @property def region(self) -> Region: return Region(self._data[ChampionMasteryData].region) @lazy_property def platform(self) -> Platform: return self.region.platform @CassiopeiaGhost.property(ChampionMasteryData) @lazy def champion(self) -> Champion: """Champion for this entry.""" return Champion( id=self._data[ChampionMasteryData].championId, region=self.region, version=get_latest_version(self.region, endpoint="champion"), ) @CassiopeiaGhost.property(ChampionMasteryData) @lazy def summoner(self) -> Summoner: """Summoner for this entry.""" return Summoner( id=self._data[ChampionMasteryData].summonerId, region=self.region ) @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on def chest_granted(self) -> bool: """Is chest granted for this champion or not in current season?""" return self._data[ChampionMasteryData].chestGranted @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on def level(self) -> int: """Champion level for specified player and champion combination.""" return self._data[ChampionMasteryData].level @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on def points(self) -> int: """Total number of champion points for this player and champion combination - used to determine champion level.""" return self._data[ChampionMasteryData].points @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on def points_until_next_level(self) -> int: """Number of points needed to achieve next level. Zero if player reached maximum champion level for this champion.""" return self._data[ChampionMasteryData].pointsUntilNextLevel @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on def tokens(self) -> int: """Number of tokens earned toward next mastery level.""" return self._data[ChampionMasteryData].tokens @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on def points_since_last_level(self) -> int: """Number of points earned since current level has been achieved. Zero if player reached maximum champion level for this champion.""" return self._data[ChampionMasteryData].pointsSinceLastLevel @CassiopeiaGhost.property(ChampionMasteryData) @ghost_load_on @lazy def last_played(self) -> arrow.Arrow: """Last time this champion was played by this player.""" return arrow.get(self._data[ChampionMasteryData].lastPlayed / 1000)
mit
bdb64ebd5f088f9b795e987843198573
32.272727
141
0.60306
3.568643
false
false
false
false
rollbar/pyrollbar
rollbar/examples/fastapi/app_middleware.py
1
1675
#!/usr/bin/env python # This example uses Uvicorn package that must be installed. However, it can be # replaced with any other ASGI-compliant server. # # Optional asynchronous reporting requires HTTPX package to be installed. # # NOTE: FastAPI middlewares don't allow to collect streamed content like a request body. # You may consider to use routing integration instead (see app.py example). # # Run: python app_middleware.py import fastapi import rollbar import uvicorn from rollbar.contrib.fastapi import ReporterMiddleware as RollbarMiddleware # Initialize Rollbar SDK with your server-side ACCESS_TOKEN rollbar.init( 'ACCESS_TOKEN', environment='staging', handler='async', # For asynchronous reporting use: default, async or httpx ) # Integrate Rollbar with FastAPI application app = fastapi.FastAPI() app.add_middleware(RollbarMiddleware) # should be added as the first middleware # Verify application runs correctly # # $ curl http://localhost:8888 @app.get('/') async def read_root(): return {'hello': 'world'} # Cause an uncaught exception to be sent to Rollbar # GET query params will be sent to Rollbar and available in the UI # # $ curl http://localhost:8888/error?param1=hello&param2=world async def localfunc(arg1, arg2, arg3): # Both local variables and function arguments will be sent to Rollbar # and available in the UI localvar = 'local variable' cause_error_with_local_variables @app.get('/error') async def read_error(): await localfunc('func_arg1', 'func_arg2', 1) return {'result': "You shouldn't be seeing this"} if __name__ == '__main__': uvicorn.run(app, host='localhost', port=8888)
mit
02d174e29ace4678bf99c44ca6b97f74
28.385965
88
0.733731
3.56383
false
false
false
false
rollbar/pyrollbar
rollbar/contrib/rq/__init__.py
5
1668
""" Exception handler hook for RQ (http://python-rq.org/) How to use: 1. Instead of using the default "rqworker" script to run the worker, write your own short script as shown in this example: https://github.com/nvie/rq/blob/master/examples/run_worker.py 2. In this script, initialize rollbar with `handler='blocking'`, for example: rollbar.init('your access token', 'production', handler='blocking') 3. After constructing the worker but before calling `.work()`, add `rollbar.contrib.rq.exception_handler` as an exception handler. Full example: ``` import rollbar from rq import Connection, Queue, Worker if __name__ == '__main__': rollbar.init('your_access_token', 'production', handler='blocking') with Connection(): q = Queue() worker = Worker(q) worker.push_exc_handler(rollbar.contrib.rq.exception_handler) worker.work() ``` """ import rollbar def exception_handler(job, *exc_info): """ Called by RQ when there is a failure in a worker. NOTE: Make sure that in your RQ worker process, rollbar.init() has been called with handler='blocking'. The default handler, 'thread', does not work from inside an RQ worker. """ # Report data about the job with the exception. job_info = job.to_dict() # job_info['data'] is the pickled representation of the job, and doesn't json-serialize well. # repr() works nicely. job_info['data'] = repr(job_info['data']) extra_data = {'job': job_info} payload_data = {'framework': 'rq'} rollbar.report_exc_info(exc_info, extra_data=extra_data, payload_data=payload_data) # continue to the next handler return True
mit
d0db574ae39da031ae29979878329b72
29.327273
97
0.682854
3.618221
false
false
false
false
meraki-analytics/cassiopeia
cassiopeia/datastores/uniquekeys.py
1
85975
from typing import ( Tuple, Set, Union, MutableMapping, Any, Mapping, Iterable, Generator, List, ) from datapipelines import Query, PipelineContext, QueryValidationError from ..data import Region, Platform, Continent, Queue, Tier, Division from ..dto.champion import ChampionRotationDto from ..dto.championmastery import ( ChampionMasteryDto, ChampionMasteryListDto, ChampionMasteryScoreDto, ) from ..dto.league import LeagueEntriesDto, LeagueSummonerEntriesDto, LeagueEntryDto from ..dto.staticdata import ( ChampionDto, ChampionListDto, ItemDto, ItemListDto, LanguageStringsDto, LanguagesDto, ProfileIconDataDto, ProfileIconDetailsDto, RealmDto, RuneDto, RuneListDto, SummonerSpellDto, SummonerSpellListDto, MapDto, MapListDto, VersionListDto, ) from ..dto.status import ShardStatusDto from ..dto.match import MatchDto, MatchReferenceDto, TimelineDto from ..dto.spectator import CurrentGameInfoDto, FeaturedGamesDto from ..dto.summoner import SummonerDto from ..core.championmastery import ChampionMastery, ChampionMasteries from ..core.league import ( LeagueSummonerEntries, ChallengerLeague, GrandmasterLeague, MasterLeague, League, LeagueEntry, ) from ..core.staticdata import ( Champion, Rune, Item, SummonerSpell, Map, Locales, LanguageStrings, ProfileIcon, ProfileIcons, Realms, Versions, Items, Champions, Maps, SummonerSpells, Runes, ) from ..core.status import ShardStatus from ..core.match import Match, MatchHistory, Timeline from ..core.summoner import Summoner from ..core.spectator import CurrentMatch, FeaturedMatches, CurrentGameParticipantData from ..core.champion import ChampionRotation, ChampionRotationData from ..core.staticdata.champion import ChampionData from ..core.staticdata.item import ItemData from ..core.staticdata.summonerspell import SummonerSpellData from ..core.staticdata.rune import RuneData from ..core.staticdata.map import MapData from ..core.summoner import SummonerData ############# # Utilities # ############# def _rgetattr(obj, key): """Recursive getattr for handling dots in keys.""" for k in key.split("."): obj = getattr(obj, k) return obj def _hash_included_data(included_data: Set[str]) -> int: return hash(tuple(included_data)) def _get_default_version(query: Mapping[str, Any], context: PipelineContext) -> str: try: pipeline = context[PipelineContext.Keys.PIPELINE] versions = pipeline.get(VersionListDto, {"platform": query["platform"]}) return versions["versions"][0] except TypeError as error: raise KeyError("`version` must be provided in query") from error def _get_default_locale(query: Mapping[str, Any], context: PipelineContext) -> str: return query["platform"].default_locale def _region_to_platform_generator( regions: Iterable[Region], ) -> Generator[Platform, None, None]: for region in regions: try: yield Region(region).platform except ValueError as e: raise QueryValidationError from e def convert_region_to_platform(query: MutableMapping[str, Any]) -> None: if "region" in query and "platform" not in query: try: query["platform"] = Region(query["region"]).platform except ValueError as e: raise QueryValidationError from e if "regions" in query and "platforms" not in query: query["platforms"] = _region_to_platform_generator(query["regions"]) if "region" in query and not isinstance(query["region"], Region): query["region"] = Region(query["region"]) def convert_to_continent(query: MutableMapping[str, Any]) -> None: if "continent" in query and not isinstance(query["continent"], Continent): query["continent"] = Continent(query["continent"]) if "region" in query and not isinstance(query["region"], Region): query["region"] = Region(query["region"]) if "platform" in query and not isinstance(query["platform"], Platform): query["platform"] = Platform(query["platform"]) if "region" in query and "platform" not in query: query["platform"] = query["region"].platform if "platform" in query and "region" not in query: query["region"] = query["platform"].region if "continent" not in query: query["continent"] = query["region"].continent ####### # DTO # ####### ################ # Champion API # ################ validate_champion_rotation_dto_query = Query.has("platform").as_(Platform) validate_many_champion_rotation_dto_query = Query.has("platform").as_(Platform) def for_champion_rotation_dto(champion_rotation: ChampionRotationDto) -> str: return champion_rotation["platform"] def for_champion_rotation_dto_query(query: Query) -> str: return query["platform"].value def for_many_champion_rotation_dto_query(query: Query) -> Generator[str, None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value except ValueError as e: raise QueryValidationError from e ######################## # Champion Mastery API # ######################## validate_champion_mastery_dto_query = ( Query.has("platform") .as_(Platform) .also.has("playerId") .as_(str) .also.has("championId") .as_(int) ) validate_many_champion_mastery_dto_query = ( Query.has("platform") .as_(Platform) .also.has("playerId") .as_(str) .also.has("championIds") .as_(Iterable) ) def for_champion_mastery_dto( champion_mastery: ChampionMasteryDto, ) -> Tuple[str, str, int]: return ( champion_mastery["platform"], champion_mastery["playerId"], champion_mastery["championId"], ) def for_champion_mastery_dto_query(query: Query) -> Tuple[str, str, int]: return query["platform"].value, query["playerId"], query["championId"] def for_many_champion_mastery_dto_query( query: Query, ) -> Generator[Tuple[str, str, int], None, None]: for champion_id in query["championIds"]: try: champion_id = int(champion_id) yield query["platform"].value, query["playerId"], champion_id except ValueError as e: raise QueryValidationError from e validate_champion_mastery_list_dto_query = ( Query.has("platform").as_(Platform).also.has("playerId").as_(str) ) validate_many_champion_mastery_list_dto_query = ( Query.has("platform").as_(Platform).also.has("playerIds").as_(Iterable) ) def for_champion_mastery_list_dto( champion_mastery_list: ChampionMasteryListDto, ) -> Tuple[str, str]: return champion_mastery_list["platform"], champion_mastery_list["playerId"] def for_champion_mastery_list_dto_query(query: Query) -> Tuple[str, str]: return query["platform"].value, query["playerId"] def for_many_champion_mastery_list_dto_query( query: Query, ) -> Generator[Tuple[str, str], None, None]: for summoner_id in query["playerIds"]: try: yield query["platform"].value, summoner_id except ValueError as e: raise QueryValidationError from e validate_champion_mastery_score_dto_query = ( Query.has("platform").as_(Platform).also.has("playerId").as_(str) ) validate_many_champion_mastery_score_dto_query = ( Query.has("platform").as_(Platform).also.has("playerIds").as_(Iterable) ) def for_champion_mastery_score_dto( champion_mastery_score: ChampionMasteryScoreDto, ) -> Tuple[str, str]: return champion_mastery_score["platform"], champion_mastery_score["playerId"] def for_champion_mastery_score_dto_query(query: Query) -> Tuple[str, str]: return query["platform"].value, query["playerId"] def for_many_champion_mastery_score_dto_query( query: Query, ) -> Generator[Tuple[str, str], None, None]: for summoner_id in query["playerIds"]: try: yield query["platform"].value, summoner_id except ValueError as e: raise QueryValidationError from e ############## # League API # ############## validate_league_entries_dto_query = ( Query.has("platform") .as_(Platform) .also.has("queue") .as_(Queue) .also.has("tier") .as_(Tier) .also.has("page") .as_(int) .also.has("id") .as_(int) ) # League ID def for_league_entries_dto( league_entries: LeagueEntriesDto, ) -> Tuple[str, str, str, int, int]: return ( league_entries["platform"], league_entries["queue"], league_entries["tier"], league_entries["id"], league_entries["page"], ) def for_league_entries_dto_query(query: Query) -> Tuple[str, str, str, int, int]: return ( query["platform"].value, query["queue"].value, query["tier"].value, query["id"], query["page"], ) validate_league_summoner_entries_dto_query = ( Query.has("platform").as_(Platform).also.has("id").as_(int) ) # Summoner ID def for_league_summoner_entries_dto( league_entries: LeagueEntriesDto, ) -> Tuple[str, int]: return league_entries["platform"], league_entries["id"] def for_league_summoner_entries_dto_query(query: Query) -> Tuple[str, int]: return query["platform"].value, query["id"] ################### # Static Data API # ################### # Champion validate_champion_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_champion_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_champion_dto( champion: ChampionDto, identifier: str = "id" ) -> Tuple[str, str, str, int, Union[int, str]]: return ( champion["platform"], champion["version"], champion["locale"], _hash_included_data(champion["includedData"]), champion[identifier], ) def for_champion_dto_query(query: Query) -> Tuple[str, str, str, int, Union[int, str]]: identifier = "id" if "id" in query else "name" return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), query[identifier], ) def for_many_champion_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: identifiers, identifier_type = ( (query["ids"], int) if "ids" in query else (query["names"], str) ) included_data_hash = _hash_included_data(query["includedData"]) for identifier in identifiers: try: identifier = identifier_type(identifier) yield query["platform"].value, query["version"], query[ "locale" ], included_data_hash, identifier except ValueError as e: raise QueryValidationError from e validate_champion_list_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_champion_list_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_champion_list_dto(champion_list: ChampionListDto) -> Tuple[str, str, str, int]: return ( champion_list["platform"], champion_list["version"], champion_list["locale"], _hash_included_data(champion_list["includedData"]), ) def for_champion_list_dto_query(query: Query) -> Tuple[str, str, str, int]: return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), ) def for_many_champion_list_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"], included_data_hash except ValueError as e: raise QueryValidationError from e # Item validate_item_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_item_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("name") .as_(Iterable) ) def for_item_dto( item: ItemDto, identifier: str = "id" ) -> Tuple[str, str, str, int, Union[int, str]]: return ( item["platform"], item["version"], item["locale"], _hash_included_data(item["includedData"]), item[identifier], ) def for_item_dto_query(query: Query) -> Tuple[str, str, str, int, Union[int, str]]: identifier = "id" if "id" in query else "name" return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), query[identifier], ) def for_many_item_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: identifiers, identifier_type = ( (query["ids"], int) if "ids" in query else (query["names"], str) ) included_data_hash = _hash_included_data(query["includedData"]) for identifier in identifiers: try: identifier = identifier_type(identifier) yield query["platform"].value, query["version"], query[ "locale" ], included_data_hash, identifier except ValueError as e: raise QueryValidationError from e validate_item_list_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_item_list_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_item_list_dto(item_list: ItemListDto) -> Tuple[str, str, str, int]: return ( item_list["platform"], item_list["version"], item_list["locale"], _hash_included_data(item_list["includedData"]), ) def for_item_list_dto_query(query: Query) -> Tuple[str, str, str, int]: return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), ) def for_many_item_list_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"], included_data_hash except ValueError as e: raise QueryValidationError from e # Language validate_language_strings_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) validate_many_language_strings_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) def for_language_strings_dto( language_strings: LanguageStringsDto, ) -> Tuple[str, str, str]: return ( language_strings["platform"], language_strings["version"], language_strings["locale"], ) def for_language_strings_dto_query(query: Query) -> Tuple[str, str, str]: return query["platform"].value, query["version"], query["locale"] def for_many_language_strings_dto_query( query: Query, ) -> Generator[Tuple[str, str, str], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"] except ValueError as e: raise QueryValidationError from e validate_languages_dto_query = Query.has("platform").as_(Platform) validate_many_languages_dto_query = Query.has("platforms").as_(Iterable) def for_languages_dto(languages: LanguagesDto) -> str: return languages["platform"] def for_languages_dto_query(query: Query) -> str: return query["platform"].value def for_many_languages_dto_query(query: Query) -> Generator[str, None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value except ValueError as e: raise QueryValidationError from e # Map validate_map_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("mapId") .as_(int) .or_("mapName") .as_(str) ) validate_many_map_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("mapIds") .as_(Iterable) .or_("mapNames") .as_(Iterable) ) def for_map_dto( map: MapDto, identifier: str = "mapId" ) -> Tuple[str, str, str, Union[int, str]]: return map["platform"], map["version"], map["locale"], map[identifier] def for_map_dto_query(query: Query) -> Tuple[str, str, str, Union[int, str]]: identifier = "mapId" if "mapId" in query else "mapName" return query["platform"].value, query["version"], query["locale"], query[identifier] def for_many_map_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, Union[int, str]], None, None]: identifiers, identifier_type = ( (query["mapIds"], int) if "mapIds" in query else (query["mapNames"], str) ) for identifier in identifiers: try: identifier = identifier_type(identifier) yield query["platform"].value, query["version"], query["locale"], identifier except ValueError as e: raise QueryValidationError from e validate_map_list_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) validate_many_map_list_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) def for_map_list_dto(map_list: MapListDto) -> Tuple[str, str, str]: return map_list["platform"], map_list["version"], map_list["locale"] def for_map_list_dto_query(query: Query) -> Tuple[str, str, str]: return query["platform"].value, query["version"], query["locale"] def for_many_map_list_dto_query( query: Query, ) -> Generator[Tuple[str, str, str], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"] except ValueError as e: raise QueryValidationError from e # Profile Icon validate_profile_icon_data_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) validate_many_profile_icon_data_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) def for_profile_icon_data_dto( profile_icon_data: ProfileIconDataDto, ) -> Tuple[str, str, str]: return ( profile_icon_data["platform"], profile_icon_data["version"], profile_icon_data["locale"], ) def for_profile_icon_data_dto_query(query: Query) -> Tuple[str, str, str]: return query["platform"].value, query["version"], query["locale"] def for_many_profile_icon_data_dto_query( query: Query, ) -> Generator[Tuple[str, str, str], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"] except ValueError as e: raise QueryValidationError from e validate_profile_icon_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("id") .as_(int) ) validate_many_profile_icon_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("ids") .as_(Iterable) ) def for_profile_icon_dto( profile_icon: ProfileIconDetailsDto, ) -> Tuple[str, str, str, int]: return ( profile_icon["platform"], profile_icon["version"], profile_icon["locale"], profile_icon["id"], ) def for_profile_icon_dto_query(query: Query) -> Tuple[str, str, str, int]: return query["platform"].value, query["version"], query["locale"], query["id"] def for_many_profile_icon_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int], None, None]: for id in query["ids"]: try: id = int(id) yield query["platform"].value, query["version"], query["locale"], id except ValueError as e: raise QueryValidationError from e # Realm validate_realm_dto_query = Query.has("platform").as_(Platform) validate_many_realm_dto_query = Query.has("platforms").as_(Iterable) def for_realm_dto(realm: RealmDto) -> str: return realm["platform"] def for_realm_dto_query(query: Query) -> str: return query["platform"].value def for_many_realm_dto_query(query: Query) -> Generator[str, None, None]: return query["platform"].value # Rune validate_rune_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_rune_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_rune_dto( rune: RuneDto, identifier: str = "id" ) -> Tuple[str, str, str, int, Union[int, str]]: return ( rune["platform"], rune["version"], rune["locale"], _hash_included_data(rune["includedData"]), rune[identifier], ) def for_rune_dto_query(query: Query) -> Tuple[str, str, str, int, Union[int, str]]: identifier = "id" if "id" in query else "name" return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), query[identifier], ) def for_many_rune_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: identifiers, identifier_type = ( (query["ids"], int) if "ids" in query else (query["names"], str) ) included_data_hash = _hash_included_data(query["includedData"]) for identifier in identifiers: try: identifier = identifier_type(identifier) yield query["platform"].value, query["version"], query[ "locale" ], included_data_hash, identifier except ValueError as e: raise QueryValidationError from e validate_rune_list_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_rune_list_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_rune_list_dto(rune_list: RuneListDto) -> Tuple[str, str, str, int]: return ( rune_list["platform"], rune_list["version"], rune_list["locale"], _hash_included_data(rune_list["includedData"]), ) def for_rune_list_dto_query(query: Query) -> Tuple[str, str, str, int]: return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), ) def for_many_rune_list_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"], included_data_hash except ValueError as e: raise QueryValidationError from e # Summoner Spell validate_summoner_spell_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_summoner_spell_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_summoner_spell_dto( summoner_spell: SummonerSpellDto, identifier: str = "id" ) -> Tuple[str, str, str, int, Union[int, str]]: return ( summoner_spell["platform"], summoner_spell["version"], summoner_spell["locale"], _hash_included_data(summoner_spell["includedData"]), summoner_spell[identifier], ) def for_summoner_spell_dto_query( query: Query, ) -> Tuple[str, str, str, int, Union[int, str]]: identifier = "id" if "id" in query else "name" return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), query[identifier], ) def for_many_summoner_spell_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: identifiers, identifier_type = ( (query["ids"], int) if "ids" in query else (query["names"], str) ) included_data_hash = _hash_included_data(query["includedData"]) for identifier in identifiers: try: identifier = identifier_type(identifier) yield query["platform"].value, query["version"], query[ "locale" ], included_data_hash, identifier except ValueError as e: raise QueryValidationError from e validate_summoner_spell_list_dto_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_summoner_spell_list_dto_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_summoner_spell_list_dto( summoner_spell_list: SummonerSpellListDto, ) -> Tuple[str, str, str, int]: return ( summoner_spell_list["platform"], summoner_spell_list["version"], summoner_spell_list["locale"], _hash_included_data(summoner_spell_list["includedData"]), ) def for_summoner_spell_list_dto_query(query: Query) -> Tuple[str, str, str, int]: return ( query["platform"].value, query["version"], query["locale"], _hash_included_data(query["includedData"]), ) def for_many_summoner_spell_list_dto_query( query: Query, ) -> Generator[Tuple[str, str, str, int], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value, query["version"], query["locale"], included_data_hash except ValueError as e: raise QueryValidationError from e # Version validate_version_list_dto_query = Query.has("platform").as_(Platform) validate_many_version_list_dto_query = Query.has("platforms").as_(Iterable) def for_version_list_dto(version_list: VersionListDto) -> str: return version_list["platform"] def for_version_list_dto_query(query: Query) -> str: return query["platform"].value def for_many_version_list_dto_query(query: Query) -> Generator[str, None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value except ValueError as e: raise QueryValidationError from e ############## # Status API # ############## validate_shard_status_dto_query = Query.has("platform").as_(Platform) validate_many_shard_status_dto_query = Query.has("platforms").as_(Iterable) def for_shard_status_dto(shard_status: ShardStatusDto) -> str: return shard_status["platform"] def for_shard_status_dto_query(query: Query) -> str: return query["platform"].value def for_many_shard_status_dto_query(query: Query) -> Generator[str, None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value except ValueError as e: raise QueryValidationError from e ############# # Match API # ############# validate_match_dto_query = ( Query.has("continent") .as_(Continent) .or_("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("id") .as_(str) ) validate_many_match_dto_query = ( Query.has("continent") .as_(Continent) .or_("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("ids") .as_(Iterable) ) def for_match_dto(match: MatchDto) -> Tuple[str, str]: return match["continent"], match["id"] def for_match_dto_query(query: Query) -> Tuple[str, str]: convert_to_continent(query) return query["continent"].value, query["id"] def for_many_match_dto_query(query: Query) -> Generator[Tuple[str, str], None, None]: convert_to_continent(query) for match_id in query["ids"]: try: yield query["continent"].value, match_id except ValueError as e: raise QueryValidationError from e validate_match_reference_dto_query = ( Query.has("continent") .as_(Continent) .or_("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("id") .as_(str) ) validate_many_match_reference_dto_query = ( Query.has("continent") .as_(Continent) .or_("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("ids") .as_(Iterable) ) def for_match_reference_dto(match_reference: MatchReferenceDto) -> Tuple[str, str]: return match_reference["continent"], match_reference["id"] def for_match_reference_dto_query(query: Query) -> Tuple[str, str]: convert_to_continent(query) return query["continent"].value, query["id"] def for_many_match_reference_dto_query( query: Query, ) -> Generator[Tuple[str, str], None, None]: convert_to_continent(query) for game_id in query["ids"]: try: yield query["continent"].value, game_id except ValueError as e: raise QueryValidationError from e validate_match_timeline_dto_query = ( Query.has("continent") .as_(Continent) .or_("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("id") .as_(str) ) validate_many_match_timeline_dto_query = ( Query.has("continent") .as_(Continent) .or_("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("ids") .as_(Iterable) ) def for_match_timeline_dto(match_timeline: TimelineDto) -> Tuple[str, str]: return match_timeline["continent"], match_timeline["id"] def for_match_timeline_dto_query(query: Query) -> Tuple[str, str]: convert_to_continent(query) return query["continent"].value, query["id"] def for_many_match_timeline_dto_query( query: Query, ) -> Generator[Tuple[str, str], None, None]: convert_to_continent(query) for match_id in query["ids"]: try: yield query["continent"].value, match_id except ValueError as e: raise QueryValidationError from e ################# # Spectator API # ################# validate_current_game_info_dto_query = ( Query.has("platform").as_(Platform).also.has("gameId").as_(int) ) validate_many_current_game_info_dto_query = ( Query.has("platform").as_(Platform).also.has("gameIds").as_(Iterable) ) def for_current_game_info_dto(current_game_info: CurrentGameInfoDto) -> Tuple[str, int]: return current_game_info["platform"], current_game_info["gameId"] def for_current_game_info_dto_query(query: Query) -> Tuple[str, int]: return query["platform"].value, query["gameId"] def for_many_current_game_info_dto_query( query: Query, ) -> Generator[Tuple[str, int], None, None]: for game_id in query["gameIds"]: try: game_id = int(game_id) yield query["platform"].value, game_id except ValueError as e: raise QueryValidationError from e validate_featured_game_dto_query = Query.has("platform").as_(Platform) validate_many_featured_game_dto_query = Query.has("platforms").as_(Iterable) def for_featured_games_dto(featured_games: FeaturedGamesDto) -> str: return featured_games["platform"] def for_featured_games_dto_query(query: Query) -> str: return query["platform"].value def for_many_featured_games_dto_query(query: Query) -> Generator[str, None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield platform.value except ValueError as e: raise QueryValidationError from e ################ # Summoner API # ################ validate_summoner_dto_query = ( Query.has("platform") .as_(Platform) .also.has("id") .as_(int) .or_("accountId") .as_(int) .or_("name") .as_(str) ) validate_many_summoner_dto_query = ( Query.has("platform") .as_(Platform) .also.has("ids") .as_(Iterable) .or_("accountIds") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_summoner_dto( summoner: SummonerDto, identifier: str = "id" ) -> Tuple[str, Union[int, str]]: return summoner["platform"], summoner[identifier] def for_summoner_dto_query(query: Query) -> Tuple[str, Union[int, str]]: if "id" in query: identifier = "id" elif "accountId" in query: identifier = "accountId" else: identifier = "name" return query["platform"].value, query[identifier] def for_many_summoner_dto_query( query: Query, ) -> Generator[Tuple[str, Union[int, str]], None, None]: if "ids" in query: identifiers, identifier_type = query["ids"], int elif "accountIds" in query: identifiers, identifier_type = query["accountIds"], int else: identifiers, identifier_type = query["names"], str for identifier in identifiers: try: identifier = identifier_type(identifier) yield query["platform"].value, identifier except ValueError as e: raise QueryValidationError from e ######## # Core # ######## ################ # Champion API # ################ validate_champion_rotation_query = Query.has("platform").as_(Platform) validate_many_champion_rotation_query = Query.has("platform").as_(Platform) def for_champion_rotation(champion_rotation: ChampionRotationData) -> List[Region]: keys = [champion_rotation.platform] return keys def for_champion_rotation_query(query: Query) -> List[str]: keys = [query["platform"].value] return keys ######################## # Champion Mastery API # ######################## validate_champion_mastery_query = ( Query.has("platform") .as_(Platform) .also.has("summoner.id") .as_(str) .or_("summoner.accountId") .as_(str) .or_("summoner.name") .as_(str) .also.has("champion.id") .as_(int) .or_("champion.name") .as_(str) ) validate_many_champion_mastery_query = ( Query.has("platform") .as_(Platform) .also.has("summoner.id") .as_(str) .or_("summoner.accountId") .as_(str) .or_("summoner.name") .as_(str) .also.has("champions.id") .as_(Iterable) .or_("champions.name") .as_(Iterable) ) def for_champion_mastery(champion_mastery: ChampionMastery) -> List[Tuple]: keys = [] try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].id, champion_mastery.champion._data[ChampionData].id, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].id, champion_mastery.champion._data[ChampionData].name, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].name, champion_mastery.champion._data[ChampionData].id, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].name, champion_mastery.champion._data[ChampionData].name, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].account_id, champion_mastery.champion._data[ChampionData].id, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].account_id, champion_mastery.champion._data[ChampionData].name, ) ) except AttributeError: pass return keys def for_champion_mastery_query(query: Query) -> List[Tuple]: keys = [] if "summoner.id" in query and "champion.id" in query: keys.append( (query["platform"].value, query["summoner.id"], query["champion.id"]) ) if "summoner.id" in query and "champion.name" in query: keys.append( (query["platform"].value, query["summoner.id"], query["champion.name"]) ) if "summoner.name" in query and "champion.id" in query: keys.append( (query["platform"].value, query["summoner.name"], query["champion.id"]) ) if "summoner.name" in query and "champion.name" in query: keys.append( (query["platform"].value, query["summoner.name"], query["champion.name"]) ) if "summoner.accountId" in query and "champion.id" in query: keys.append( (query["platform"].value, query["summoner.accountId"], query["champion.id"]) ) if "summoner.accountId" in query and "champion.name" in query: keys.append( ( query["platform"].value, query["summoner.accountId"], query["champion.name"], ) ) return keys def for_many_champion_mastery_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: grouped_identifiers = [] identifier_types = [] if "champions.id" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(int) if "champions.name" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): identifier = identifier_type(identifier) if "summoner.id" in query: keys.append((query["platform"].value, query["summoner.id"], identifier)) if "summoner.name" in query: keys.append( (query["platform"].value, query["summoner.name"], identifier) ) if "summoner.accountId" in query: keys.append( (query["platform"].value, query["summoner.accountId"], identifier) ) if len(keys) == 0: raise QueryValidationError yield keys validate_champion_masteries_query = ( Query.has("platform") .as_(Platform) .also.has("summoner.id") .as_(str) .or_("summoner.accountId") .as_(int) .or_("summoner.name") ) validate_many_champion_masteries_query = ( Query.has("platform") .as_(Platform) .also.has("summoner.id") .as_(str) .or_("summoner.accountId") .as_(int) .or_("summoner.name") ) def for_champion_masteries(champion_mastery: ChampionMasteries) -> List[Tuple]: keys = [] try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].id, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].name, ) ) except AttributeError: pass try: keys.append( ( champion_mastery.platform.value, champion_mastery.summoner._data[SummonerData].account_id, ) ) except AttributeError: pass return keys def for_champion_masteries_query(query: Query) -> List[Tuple]: keys = [] if "summoner.id" in query: keys.append((query["platform"].value, query["summoner.id"])) if "summoner.name" in query: keys.append((query["platform"].value, query["summoner.name"])) if "summoner.accountId" in query: keys.append((query["platform"].value, query["summoner.accountId"])) return keys ############## # League API # ############## # League Entries validate_league_entries_query = ( Query.has("platform").as_(Platform).also.has("summoner.id").as_(str) ) validate_many_league_entries_query = ( Query.has("platform").as_(Platform).also.has("summoners.id").as_(Iterable) ) def for_league_summoner_entries( entries: LeagueSummonerEntries, ) -> List[Tuple[str, str]]: return [(entries.platform.value, entries._LeagueSummonerEntries__summoner.id)] def for_league_summoner_entries_query(query: Query) -> List[Tuple[str, str]]: return [(query["platform"].value, query["summoner.id"])] def for_many_league_summoner_entries_query( query: Query, ) -> Generator[List[Tuple[str, str]], None, None]: for id in query["summoners.id"]: try: yield [(query["platform"].value, id)] except ValueError as e: raise QueryValidationError from e # Leagues validate_league_query = Query.has("platform").as_(Platform).also.has("id").as_(str) validate_many_league_query = ( Query.has("platform").as_(Platform).also.has("ids").as_(Iterable) ) def for_league(league: League) -> List[Tuple[str, str]]: return [(league.platform.value, league.id)] def for_league_query(query: Query) -> List[Tuple[str, str]]: return [(query["platform"].value, query["id"])] def for_many_league_query(query: Query) -> Generator[List[Tuple[str, str]], None, None]: for id in query["ids"]: try: yield [(query["platform"].value, id)] except ValueError as e: raise QueryValidationError from e # Challenger validate_challenger_league_query = ( Query.has("platform").as_(Platform).also.has("queue").as_(Queue) ) validate_many_challenger_league_query = ( Query.has("platform").as_(Platform).also.has("queues").as_(Iterable) ) def for_challenger_league(league: ChallengerLeague) -> List[Tuple[str, str]]: return [(league.platform.value, league.queue.value)] def for_challenger_league_query(query: Query) -> List[Tuple[str, str]]: return [(query["platform"].value, query["queue"].value)] def for_many_challenger_league_query( query: Query, ) -> Generator[List[Tuple[str, str]], None, None]: for queue in query["queues"]: try: yield [(query["platform"].value, queue.value)] except ValueError as e: raise QueryValidationError from e # Grandmaster validate_grandmaster_league_query = ( Query.has("platform").as_(Platform).also.has("queue").as_(Queue) ) validate_many_grandmaster_league_query = ( Query.has("platform").as_(Platform).also.has("queues").as_(Iterable) ) def for_grandmaster_league(league: GrandmasterLeague) -> List[Tuple[str, str]]: return [(league.platform.value, league.queue.value)] def for_grandmaster_league_query(query: Query) -> List[Tuple[str, str]]: return [(query["platform"].value, query["queue"].value)] def for_many_grandmaster_league_query( query: Query, ) -> Generator[List[Tuple[str, str]], None, None]: for queue in query["queues"]: try: yield [(query["platform"].value, queue.value)] except ValueError as e: raise QueryValidationError from e # Master validate_master_league_query = ( Query.has("platform").as_(Platform).also.has("queue").as_(Queue) ) validate_many_master_league_query = ( Query.has("platform").as_(Platform).also.has("queues").as_(Iterable) ) def for_master_league(league: MasterLeague) -> List[Tuple[str, str]]: return [(league.platform.value, league.queue.value)] def for_master_league_query(query: Query) -> List[Tuple[str, str]]: return [(query["platform"].value, query["queue"].value)] def for_many_master_league_query( query: Query, ) -> Generator[List[Tuple[str, str]], None, None]: for queue in query["queues"]: try: yield [(query["platform"].value, queue.value)] except ValueError as e: raise QueryValidationError from e # League Entries List validate_league_entries_list_query = ( Query.has("queue") .as_(Queue) .also.has("tier") .as_(Tier) .also.has("division") .as_(Division) .also.has("platform") .as_(Platform) ) def for_league_entries_list( lel: LeagueSummonerEntries, ) -> List[Tuple[str, str, str, str]]: return [(lel.platform.value, lel.queue.value, lel.tier.value, lel.division.value)] def for_league_entries_list_query(query: Query) -> List[Tuple[str, str, str, str]]: return [ ( query["platform"].value, query["queue"].value, query["tier"].value, query["division"].value, ) ] ################### # Static Data API # ################### # Champion validate_champion_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_champion_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_champion(champion: Champion) -> List[Tuple]: keys = [] try: keys.append( ( champion.platform.value, champion.version, champion.locale, _hash_included_data(champion.included_data), champion._data[ChampionData].id, ) ) except AttributeError: pass try: keys.append( ( champion.platform.value, champion.version, champion.locale, _hash_included_data(champion.included_data), champion._data[ChampionData].name, ) ) except AttributeError: pass return keys def for_champion_query(query: Query) -> List[Tuple]: keys = [] included_data_hash = _hash_included_data(query["includedData"]) if "id" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["id"], ) ) if "name" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["name"], ) ) return keys def for_many_champion_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) grouped_identifiers = [] identifier_types = [] if "ids" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(int) if "names" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): try: identifier = identifier_type(identifier) keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, identifier, ) ) except ValueError as e: raise QueryValidationError from e yield keys validate_champions_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_champions_query = ( Query.has("platforms") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_champions(champions: Champions) -> List[Tuple[str, str, str, int]]: return [ ( champions.platform.value, champions.version, champions.locale, _hash_included_data(champions.included_data), ) ] def for_champions_query(query: Query) -> List[Tuple[str, str, str, int]]: included_data_hash = _hash_included_data(query["includedData"]) return [ (query["platform"].value, query["version"], query["locale"], included_data_hash) ] def for_many_champions_query( query: Query, ) -> Generator[List[Tuple[str, str, str, int, Union[int, str]]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: yield [ (platform.value, query["version"], query["locale"], included_data_hash) ] except ValueError as e: raise QueryValidationError from e # Item validate_item_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_item_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_item(item: Item) -> List[Tuple]: keys = [] try: keys.append( ( item.platform.value, item.version, item.locale, _hash_included_data(item.included_data), item._data[ItemData].id, ) ) except AttributeError: pass try: keys.append( ( item.platform.value, item.version, item.locale, _hash_included_data(item.included_data), item._data[ItemData].name, ) ) except AttributeError: pass return keys def for_item_query(query: Query) -> List[Tuple]: keys = [] included_data_hash = _hash_included_data(query["includedData"]) if "id" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["id"], ) ) if "name" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["name"], ) ) return keys def for_many_item_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) grouped_identifiers = [] identifier_types = [] if "ids" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(int) if "names" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): try: identifier = identifier_type(identifier) keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, identifier, ) ) except ValueError as e: raise QueryValidationError from e yield keys validate_items_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_items_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_items(items: Items) -> List[Tuple[str, str, str, int]]: return [ ( items.platform.value, items.version, items.locale, _hash_included_data(items.included_data), ) ] def for_items_query(query: Query) -> List[Tuple[str, str, str, int]]: included_data_hash = _hash_included_data(query["includedData"]) return [ (query["platform"].value, query["version"], query["locale"], included_data_hash) ] def for_many_items_query( query: Query, ) -> Generator[List[Tuple[str, str, str, int, Union[int, str]]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: yield [ (platform.value, query["version"], query["locale"], included_data_hash) ] except ValueError as e: raise QueryValidationError from e # Language validate_languages_query = Query.has("platform").as_(Platform) validate_many_languages_query = Query.has("platforms").as_(Iterable) def for_languages(languages: Locales) -> List[str]: return [languages.platform.value] def for_languages_query(query: Query) -> List[str]: return [query["platform"].value] def for_many_languages_query(query: Query) -> Generator[List[str], None, None]: for platform in query["platforms"]: yield [platform.value] validate_language_strings_query = Query.has("platform").as_(Platform) validate_many_language_strings_query = Query.has("platforms").as_(Iterable) def for_language_strings(languages: LanguageStrings) -> List[str]: return [languages.platform.value] def for_language_strings_query(query: Query) -> List[str]: return [query["platform"].value] def for_many_language_strings_query(query: Query) -> Generator[List[str], None, None]: for platform in query["platforms"]: yield [platform.value] # Map validate_map_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_map_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_map(map: Map) -> List[Tuple]: keys = [] try: keys.append( (map.platform.value, map.version, map.locale, map._data[MapData].id) ) except AttributeError: pass try: keys.append( (map.platform.value, map.version, map.locale, map._data[MapData].name) ) except AttributeError: pass return keys def for_map_query(query: Query) -> List[Tuple]: keys = [] if "id" in query: keys.append( (query["platform"].value, query["version"], query["locale"], query["id"]) ) if "name" in query: keys.append( (query["platform"].value, query["version"], query["locale"], query["name"]) ) return keys def for_many_map_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: grouped_identifiers = [] identifier_types = [] if "ids" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(int) if "names" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): try: identifier = identifier_type(identifier) keys.append( ( query["platform"].value, query["version"], query["locale"], identifier, ) ) except ValueError as e: raise QueryValidationError from e yield keys validate_maps_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) validate_many_maps_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) def for_maps(maps: Maps) -> List[Tuple[str, str, str]]: return [(maps.platform.value, maps.version, maps.locale)] def for_maps_query(query: Query) -> List[Tuple[str, str, str]]: return [(query["platform"].value, query["version"], query["locale"])] def for_many_maps_query( query: Query, ) -> Generator[List[Tuple[str, str, str]], None, None]: for platform in query["platforms"]: yield [(platform.value, query["version"], query["locale"])] # Profile Icon validate_profile_icons_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) validate_many_profile_icons_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) ) def for_profile_icons(profile_icon: ProfileIcons) -> List[Tuple[str, str, str]]: return [ ( Region(profile_icon.region).platform.value, profile_icon.version, profile_icon.locale, ) ] def for_profile_icons_query(query: Query) -> List[Tuple[str, str, str]]: return [(query["platform"].value, query["version"], query["locale"])] def for_many_profile_icons_query( query: Query, ) -> Generator[List[Tuple[str, str, str]], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield [(platform.value, query["version"], query["locale"])] except ValueError as e: raise QueryValidationError from e validate_profile_icon_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("id") .as_(int) ) validate_many_profile_icon_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.has("ids") .as_(Iterable) ) def for_profile_icon(profile_icon: ProfileIcon) -> List[Tuple[str, str, str, int]]: return [ ( Region(profile_icon.region).platform.value, profile_icon.version, profile_icon.locale, profile_icon.id, ) ] def for_profile_icon_query(query: Query) -> List[Tuple[str, str, str, int]]: return [(query["platform"].value, query["version"], query["locale"], query["id"])] def for_many_profile_icon_query( query: Query, ) -> Generator[List[Tuple[str, str, str, int]], None, None]: for id in query["ids"]: try: id = int(id) yield [(query["platform"].value, query["version"], query["locale"], id)] except ValueError as e: raise QueryValidationError from e # Realm validate_realms_query = Query.has("platform").as_(Platform) validate_many_realms_query = Query.has("platforms").as_(Iterable) def for_realms(realm: Realms) -> List[str]: return [(realm.platform.value)] def for_realms_query(query: Query) -> List[str]: return [(query["platform"].value)] def for_many_realms_query(query: Query) -> Generator[List[str], None, None]: for platform in query["platforms"]: yield [(platform.value)] # Rune validate_rune_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_rune_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_rune(rune: Rune) -> List[Tuple]: keys = [] try: keys.append( ( rune.platform.value, rune.version, rune.locale, _hash_included_data(rune.included_data), rune._data[RuneData].id, ) ) except AttributeError: pass try: keys.append( ( rune.platform.value, rune.version, rune.locale, _hash_included_data(rune.included_data), rune._data[RuneData].name, ) ) except AttributeError: pass return keys def for_rune_query(query: Query) -> List[Tuple]: keys = [] included_data_hash = _hash_included_data(query["includedData"]) if "id" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["id"], ) ) if "name" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["name"], ) ) return keys def for_many_rune_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) grouped_identifiers = [] identifier_types = [] if "ids" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(int) if "names" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): try: identifier = identifier_type(identifier) keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, identifier, ) ) except ValueError as e: raise QueryValidationError from e yield keys validate_runes_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_runes_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_runes(runes: Runes) -> List[Tuple[str, str, str, int]]: return [ ( runes.platform.value, runes.version, runes.locale, _hash_included_data(runes.included_data), ) ] def for_runes_query(query: Query) -> List[Tuple[str, str, str, int]]: included_data_hash = _hash_included_data(query["includedData"]) return [ (query["platform"].value, query["version"], query["locale"], included_data_hash) ] def for_many_runes_query( query: Query, ) -> Generator[List[Tuple[str, str, str, int, Union[int, str]]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: yield [ (platform.value, query["version"], query["locale"], included_data_hash) ] except ValueError as e: raise QueryValidationError from e # Summoner Spell validate_summoner_spell_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("id") .as_(int) .or_("name") .as_(str) ) validate_many_summoner_spell_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) .also.has("ids") .as_(Iterable) .or_("names") .as_(Iterable) ) def for_summoner_spell(summoner_spell: SummonerSpell) -> List[Tuple]: keys = [] try: keys.append( ( summoner_spell.platform.value, summoner_spell.version, summoner_spell.locale, _hash_included_data(summoner_spell.included_data), summoner_spell._data[SummonerSpellData].id, ) ) except AttributeError: pass try: keys.append( ( summoner_spell.platform.value, summoner_spell.version, summoner_spell.locale, _hash_included_data(summoner_spell.included_data), summoner_spell._data[SummonerSpellData].name, ) ) except AttributeError: pass return keys def for_summoner_spell_query(query: Query) -> List[Tuple]: keys = [] included_data_hash = _hash_included_data(query["includedData"]) if "id" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["id"], ) ) if "name" in query: keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, query["name"], ) ) return keys def for_many_summoner_spell_query( query: Query, ) -> Generator[Tuple[str, str, str, int, Union[int, str]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) grouped_identifiers = [] identifier_types = [] if "ids" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(int) if "names" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): try: identifier = identifier_type(identifier) keys.append( ( query["platform"].value, query["version"], query["locale"], included_data_hash, identifier, ) ) except ValueError as e: raise QueryValidationError from e yield keys validate_summoner_spells_query = ( Query.has("platform") .as_(Platform) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) validate_many_summoner_spells_query = ( Query.has("platforms") .as_(Iterable) .also.can_have("version") .with_default(_get_default_version, supplies_type=str) .also.can_have("locale") .with_default(_get_default_locale, supplies_type=str) .also.can_have("includedData") .with_default({"all"}) ) def for_summoner_spells( summoner_spells: SummonerSpells, ) -> List[Tuple[str, str, str, int]]: return [ ( summoner_spells.platform.value, summoner_spells.version, summoner_spells.locale, _hash_included_data(summoner_spells.included_data), ) ] def for_summoner_spells_query(query: Query) -> List[Tuple[str, str, str, int]]: included_data_hash = _hash_included_data(query["includedData"]) return [ (query["platform"].value, query["version"], query["locale"], included_data_hash) ] def for_many_summoner_spells_query( query: Query, ) -> Generator[List[Tuple[str, str, str, int, Union[int, str]]], None, None]: included_data_hash = _hash_included_data(query["includedData"]) for platform in query["platforms"]: try: yield [ (platform.value, query["version"], query["locale"], included_data_hash) ] except ValueError as e: raise QueryValidationError from e # Version validate_versions_query = Query.has("platform").as_(Platform) validate_many_versions_query = Query.has("platforms").as_(Iterable) def for_versions(versions: Versions) -> List[str]: return [versions.platform.value] def for_versions_query(query: Query) -> List[str]: return [query["platform"].value] def for_many_versions_query(query: Query) -> Generator[List[str], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield [platform.value] except ValueError as e: raise QueryValidationError from e ############## # Status API # ############## validate_shard_status_query = Query.has("platform").as_(Platform) validate_many_shard_status_query = Query.has("platforms").as_(Iterable) def for_shard_status(shard_status: ShardStatus) -> List[str]: return [shard_status.platform.value] def for_shard_status_query(query: Query) -> List[str]: return [query["platform"].value] def for_many_shard_status_query(query: Query) -> Generator[List[str], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield [platform.value] except ValueError as e: raise QueryValidationError from e ############# # Match API # ############# validate_match_query = ( Query.has("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("id") .as_(int) ) validate_many_match_query = ( Query.has("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("ids") .as_(Iterable) ) def for_match(match: Match) -> List[Tuple[str, str]]: return [(match.platform.value, match.id)] def for_match_query(query: Query) -> List[Tuple[str, str]]: convert_region_to_platform(query) if "region" in query: query["platform"] = query["region"].platform return [(query["platform"].value, query["id"])] def for_many_match_query(query: Query) -> Generator[List[Tuple[str, str]], None, None]: convert_region_to_platform(query) if "region" in query: query["platform"] = query["region"].platform for id in query["ids"]: try: yield [(query["platform"].value, id)] except ValueError as e: raise QueryValidationError from e validate_match_timeline_query = ( Query.has("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("id") .as_(int) ) validate_many_match_timeline_query = ( Query.has("region") .as_(Region) .or_("platform") .as_(Platform) .also.has("ids") .as_(Iterable) ) def for_match_timeline(timeline: Timeline) -> List[Tuple[str, str]]: return [(timeline.platform.value, timeline.id)] def for_match_timeline_query(query: Query) -> List[Tuple[str, str]]: convert_region_to_platform(query) return [(query["platform"].value, query["id"])] def for_many_match_timeline_query( query: Query, ) -> Generator[List[Tuple[str, str]], None, None]: convert_region_to_platform(query) for id in query["ids"]: try: yield [(query["platform"].value, id)] except ValueError as e: raise QueryValidationError from e ################# # Spectator API # ################# validate_current_match_query = ( Query.has("platform").as_(Platform).also.has("summoner.id").as_(str) ) validate_many_current_match_query = ( Query.has("platform").as_(Platform).also.has("summoner.ids").as_(Iterable) ) def for_current_match(current_match_info: CurrentMatch) -> List[Tuple[str, str]]: # Reach into the data for the summoner ids so we don't create the Summoner objects # This stores the current match for every summoner in the match, so if a different summoner is # requested, the match isn't pulled a second time. return [ ( current_match_info.platform.value, participant._data[CurrentGameParticipantData].summonerId, ) for participant in current_match_info.participants ] + [(current_match_info.platform.value, current_match_info.id)] def for_current_match_query(query: Query) -> List[Tuple[str, str]]: return [(query["platform"].value, query["summoner.id"])] def for_many_current_match_query( query: Query, ) -> Generator[List[Tuple[str, str]], None, None]: for summoner_id in query["summoner.ids"]: try: summoner_id = int(summoner_id) yield [(query["platform"].value, summoner_id)] except ValueError as e: raise QueryValidationError from e validate_featured_matches_query = Query.has("platform").as_(Platform) validate_many_featured_matches_query = Query.has("platforms").as_(Iterable) def for_featured_matches(featured_matches: FeaturedMatches) -> List[str]: return [featured_matches.platform] def for_featured_matches_query(query: Query) -> List[str]: return [query["platform"].value] def for_many_featured_matches_query(query: Query) -> Generator[List[str], None, None]: for platform in query["platforms"]: try: platform = Platform(platform) yield [platform.value] except ValueError as e: raise QueryValidationError from e ################ # Summoner API # ################ validate_summoner_query = ( Query.has("platform") .as_(Platform) .also.has("id") .as_(str) .or_("accountId") .as_(str) .or_("name") .as_(str) .or_("puuid") .as_(str) ) validate_many_summoner_query = ( Query.has("platform") .as_(Platform) .also.has("ids") .as_(Iterable) .or_("accountIds") .as_(Iterable) .or_("names") .as_(Iterable) .or_("puuids") .as_(Iterable) ) def for_summoner(summoner: Summoner) -> List[Tuple]: keys = [] try: keys.append((summoner.platform.value, "id", summoner._data[SummonerData].id)) except AttributeError: pass try: keys.append( (summoner.platform.value, "name", summoner._data[SummonerData].name) ) except AttributeError: pass try: keys.append( ( summoner.platform.value, "accountId", summoner._data[SummonerData].accountId, ) ) except AttributeError: pass try: keys.append( (summoner.platform.value, "puuid", summoner._data[SummonerData].puuid) ) except AttributeError: pass return keys def for_summoner_query(query: Query) -> List[Tuple]: keys = [] if "id" in query: keys.append((query["platform"].value, "id", query["id"])) if "name" in query: keys.append((query["platform"].value, "name", query["name"])) if "accountId" in query: keys.append((query["platform"].value, "accountId", query["accountId"])) if "puuid" in query: keys.append((query["platform"].value, "puuid", query["puuid"])) return keys def for_many_summoner_query(query: Query) -> Generator[List[Tuple], None, None]: grouped_identifiers = [] identifier_types = [] if "ids" in query: grouped_identifiers.append(query["ids"]) identifier_types.append(str) elif "accountIds" in query: grouped_identifiers.append(query["accountIds"]) identifier_types.append(str) elif "puuids" in query: grouped_identifiers.append(query["puuids"]) identifier_types.append(str) elif "names" in query: grouped_identifiers.append(query["names"]) identifier_types.append(str) for identifiers in zip(*grouped_identifiers): keys = [] for identifier, identifier_type in zip(identifiers, identifier_types): try: identifier = identifier_type(identifier) keys.append((query["platform"].value, identifier)) except ValueError as e: raise QueryValidationError from e yield keys
mit
22b657e783a4f5075803c48efbf35b78
25.766812
98
0.601035
3.506178
false
false
false
false
rollbar/pyrollbar
rollbar/lib/transforms/serializable.py
2
3783
import math from rollbar.lib import binary_type, string_types from rollbar.lib import ( circular_reference_label, float_infinity_label, float_nan_label, undecodable_object_label, unencodable_object_label) from rollbar.lib import iteritems, python_major_version, text from rollbar.lib.transforms import Transform class SerializableTransform(Transform): def __init__(self, safe_repr=True, safelist_types=None): super(SerializableTransform, self).__init__() self.safe_repr = safe_repr self.safelist = set(safelist_types or []) def transform_circular_reference(self, o, key=None, ref_key=None): return circular_reference_label(o, ref_key) def transform_namedtuple(self, o, key=None): tuple_dict = o._asdict() transformed_dict = self.transform_dict(tuple_dict, key=key) new_vals = [] for field in tuple_dict: new_vals.append(transformed_dict[field]) return '<%s>' % text(o._make(new_vals)) def transform_number(self, o, key=None): if math.isnan(o): return float_nan_label(o) elif math.isinf(o): return float_infinity_label(o) else: return o def transform_py2_str(self, o, key=None): try: o.decode('utf8') except UnicodeDecodeError: return undecodable_object_label(o) else: return o def transform_py3_bytes(self, o, key=None): try: o.decode('utf8') except UnicodeDecodeError: return undecodable_object_label(o) else: return repr(o) def transform_unicode(self, o, key=None): try: o.encode('utf8') except UnicodeEncodeError: return unencodable_object_label(o) else: return o def transform_dict(self, o, key=None): ret = {} for k, v in iteritems(o): if isinstance(k, string_types) or isinstance(k, binary_type): if python_major_version() < 3: if isinstance(k, unicode): new_k = self.transform_unicode(k) else: new_k = self.transform_py2_str(k) else: if isinstance(k, bytes): new_k = self.transform_py3_bytes(k) else: new_k = self.transform_unicode(k) else: new_k = text(k) ret[new_k] = v return super(SerializableTransform, self).transform_dict(ret, key=key) def transform_custom(self, o, key=None): if o is None: return None # Best to be very careful when we call user code in the middle of # preparing a stack trace. So we put a try/except around it all. try: if any(filter(lambda x: isinstance(o, x), self.safelist)): try: return repr(o) except TypeError: pass # If self.safe_repr is False, use repr() to serialize the object if not self.safe_repr: try: return repr(o) except TypeError: pass # Otherwise, just use the type name return str(type(o)) except Exception as e: exc_str = '' try: exc_str = str(e) except Exception as e2: exc_str = '[%s while calling str(%s)]' % ( e2.__class__.__name__, e.__class__.__name__) return '<%s in %s.__repr__: %s>' % ( e.__class__.__name__, o.__class__.__name__, exc_str) __all__ = ['SerializableTransform']
mit
a617d3f155130d08b4bfc2f61ea71a6d
31.333333
78
0.528417
4.063373
false
false
false
false
meraki-analytics/cassiopeia
examples/dtos.py
1
2536
import cassiopeia as cass from cassiopeia import Platform # On rare occasions you may want to avoid using Cass's nice type system and instead access dictionary-like objects # pulled directly from the Riot API (or other data sources). # This should be a rare use case, and it neglects the part of Cass that's fun to use (which is the interface). Instead, # you will have to create queries to Cass's datapipeline manually. This is undocumented functionality. You can look in # the files in cassiopeia/datastores/riotapi to figure out what the query parameters are. # You also need to specify the type you are requesting, which will likely be a dto type located in one of the # cassiopeia/dto files. In most cases you can also request Data types, which are located in cassiopeia/core, and the # class names end in "Data". "Data" types are an attempt to improve upon Riot's dto data format to make the data # itself easier to work with. In some instances, you may want to store Data types in your database rather than dto # types. # Below is an example of requesting a summoner dto, which is returned as a dictionary. The dictionary can be converted # to json or to msgpack bytes. msgpack is a compressed form of json that is often used for sending data over the # internet. I also included an example for pulling a match. # I can imagine you may want to use the pipeline directly if, for example, all you want you do is create a database. # In that case, you would set Cass up to use a database such as SQL, then iterate over a list of match IDs (gathered # however you want) and make a pipeline request for a MatchDto for each match ID. This would pull the match data from # Riot and populate your database with the MatchDto data. This will be faster than doing the same thing using Cass's # core interface, but the logic will be more complex and there may be some nuanced issues that you'll have to figure # out. def use_pipeline(): pipeline = cass._get_pipeline() summoner_dto = pipeline.get( cass.dto.summoner.SummonerDto, query={"name": "Kalturi", "platform": Platform.north_america}, ) print(summoner_dto) print(summoner_dto.to_json(indent=2)) print(summoner_dto.to_bytes()) # Requires `pip install msgpack` print() match_dto = pipeline.get( cass.dto.match.MatchDto, query={"id": 3000332065, "platform": Platform.north_america}, ) print(match_dto.keys()) print(match_dto["gameCreation"]) if __name__ == "__main__": use_pipeline()
mit
6c07178e3f714e1048807d3854ef7bde
52.957447
119
0.734621
3.633238
false
false
false
false
kemayo/sublime-text-git
git/history.py
1
9932
from __future__ import absolute_import, unicode_literals, print_function, division import functools import re import sublime from . import GitTextCommand, GitWindowCommand, plugin_file class GitBlameCommand(GitTextCommand): def run(self, edit): # somewhat custom blame command: # -w: ignore whitespace changes # -M: retain blame when moving lines # -C: retain blame when copying lines between files command = ['git', 'blame', '-w', '-M', '-C'] line_ranges = [self.get_lines(selection) for selection in self.view.sel() if not selection.empty()] if line_ranges: for (range_start, range_end, *line_range_len) in line_ranges: command.extend(('-L', str(range_start) + ',' + str(range_end))) callback = self.blame_done else: callback = functools.partial(self.blame_done, focused_line=self.get_current_line()) command.append(self.get_file_name()) self.run_command(command, callback) def get_current_line(self): (current_line, column) = self.view.rowcol(self.view.sel()[0].a) # line is 1 based return current_line + 1 def get_lines(self, selection): if selection.empty(): return False # just the lines we have a selection on begin_line, begin_column = self.view.rowcol(selection.begin()) end_line, end_column = self.view.rowcol(selection.end()) # blame will fail if last line is empty and is included in the selection if end_line > begin_line and end_column == 0: end_line -= 1 # add one to each, to line up sublime's index with git's return begin_line + 1, end_line + 1 def blame_done(self, result, focused_line=1): self.scratch( result, title="Git Blame", focused_line=focused_line, syntax=plugin_file("syntax/Git Blame.tmLanguage") ) class GitLog(object): def run(self, edit=None): fn = self.get_file_name() return self.run_log(fn != '', '--', fn) def run_log(self, follow, *args): # the ASCII bell (\a) is just a convenient character I'm pretty sure # won't ever come up in the subject of the commit (and if it does then # you positively deserve broken output...) # 9000 is a pretty arbitrarily chosen limit; picked entirely because # it's about the size of the largest repo I've tested this on... and # there's a definite hiccup when it's loading that command = [ 'git', 'log', '--no-color', '--pretty=%s (%h)\a%an <%aE>\a%ad (%ar)', '--date=local', '--max-count=9000', '--follow' if follow else None ] command.extend(args) self.run_command( command, self.log_done) def log_done(self, result): self.results = [r.split('\a', 2) for r in result.strip().split('\n')] self.quick_panel(self.results, self.log_panel_done) def log_panel_done(self, picked): if 0 > picked < len(self.results): return item = self.results[picked] # the commit hash is the last thing on the first line, in brackets ref = item[0].split(' ')[-1].strip('()') self.log_result(ref) def log_result(self, ref): # I'm not certain I should have the file name here; it restricts the # details to just the current file. Depends on what the user expects... # which I'm not sure of. self.run_command( ['git', 'log', '--no-color', '-p', '-1', ref, '--', self.get_file_name()], self.details_done) def details_done(self, result): self.scratch(result, title="Git Commit Details", syntax=plugin_file("syntax/Git Commit View.tmLanguage")) class GitLogCommand(GitLog, GitTextCommand): pass class GitLogAllCommand(GitLog, GitWindowCommand): pass class GitShow(object): def run(self, edit=None): # GitLog Copy-Past self.run_command( ['git', 'log', '--no-color', '--pretty=%s (%h)\a%an <%aE>\a%ad (%ar)', '--date=local', '--max-count=9000', '--', self.get_file_name()], self.show_done) def show_done(self, result): # GitLog Copy-Past self.results = [r.split('\a', 2) for r in result.strip().split('\n')] self.quick_panel(self.results, self.panel_done) def panel_done(self, picked): if 0 > picked < len(self.results): return item = self.results[picked] # the commit hash is the last thing on the first line, in brackets ref = item[0].split(' ')[-1].strip('()') self.run_command( ['git', 'show', '%s:%s' % (ref, self.get_relative_file_path())], self.details_done, ref=ref) def details_done(self, result, ref): syntax = self.view.settings().get('syntax') self.scratch(result, title="%s:%s" % (ref, self.get_file_name()), syntax=syntax) class GitShowCommand(GitShow, GitTextCommand): pass class GitShowAllCommand(GitShow, GitWindowCommand): pass class GitShowCommitCommand(GitWindowCommand): def run(self, edit=None): self.window.show_input_panel("Commit to show:", "", self.input_done, None, None) def input_done(self, commit): commit = commit.strip() self.run_command(['git', 'show', commit, '--'], self.show_done, commit=commit) def show_done(self, result, commit): if result.startswith('fatal:'): self.panel(result) return self.scratch(result, title="Git Commit: %s" % commit, syntax=plugin_file("syntax/Git Commit View.tmLanguage")) class GitGraph(object): def run(self, edit=None): filename = self.get_file_name() self.run_command( ['git', 'log', '--graph', '--pretty=%h -%d (%cr) (%ci) <%an> %s', '--abbrev-commit', '--no-color', '--decorate', '--date=relative', '--follow' if filename else None, '--', filename], self.log_done ) def log_done(self, result): self.scratch(result, title="Git Log Graph", syntax=plugin_file("syntax/Git Graph.tmLanguage")) class GitGraphCommand(GitGraph, GitTextCommand): pass class GitGraphAllCommand(GitGraph, GitWindowCommand): pass class GitOpenFileCommand(GitLog, GitWindowCommand): def run(self): self.run_command(['git', 'branch', '-a', '--no-color'], self.branch_done) def branch_done(self, result): self.results = result.rstrip().split('\n') self.quick_panel( self.results, self.branch_panel_done, sublime.MONOSPACE_FONT ) def branch_panel_done(self, picked): if 0 > picked < len(self.results): return self.branch = self.results[picked].split(' ')[-1] self.run_log(False, self.branch) def log_result(self, result_hash): self.ref = result_hash self.run_command( ['git', 'ls-tree', '-r', '--full-tree', self.ref], self.ls_done) def ls_done(self, result): # Last two items are the ref and the file name # p.s. has to be a list of lists; tuples cause errors later self.results = [[match.group(2), match.group(1)] for match in re.finditer(r"\S+\s(\S+)\t(.+)", result)] self.quick_panel(self.results, self.ls_panel_done) def ls_panel_done(self, picked): if 0 > picked < len(self.results): return item = self.results[picked] self.filename = item[0] self.fileRef = item[1] self.run_command( ['git', 'show', self.fileRef], self.show_done) def show_done(self, result): self.scratch(result, title="%s:%s" % (self.fileRef, self.filename)) class GitDocumentCommand(GitBlameCommand): def blame_done(self, result, focused_line=1): shas = set((sha for sha in re.findall(r'^[0-9a-f]+', result, re.MULTILINE) if not re.match(r'^0+$', sha))) command = ['git', 'show', '-s', '-z', '--no-color', '--date=iso'] command.extend(shas) self.run_command(command, self.show_done) def show_done(self, result): commits = [] for commit in result.split('\0'): match = re.search(r'^Date:\s+(.+)$', commit, re.MULTILINE) if match: commits.append((match.group(1), commit)) commits.sort(reverse=True) commits = [commit for d, commit in commits] self.scratch('\n\n'.join(commits), title="Git Commit Documentation", syntax=plugin_file("syntax/Git Commit View.tmLanguage")) class GitGotoCommit(GitTextCommand): def run(self, edit): view = self.view # Sublime is missing a "find scope in region" API, so we piece one together here: lines = [view.line(sel.a) for sel in view.sel()] hashes = self.view.find_by_selector("string.sha") commits = [] for region in hashes: for line in lines: if line.contains(region): commit = view.substr(region) if commit.strip("0"): commits.append(commit) break working_dir = view.settings().get("git_root_dir") for commit in commits: self.run_command(['git', 'show', commit], self.show_done, working_dir=working_dir) def show_done(self, result): self.scratch(result, title="Git Commit View", syntax=plugin_file("syntax/Git Commit View.tmLanguage")) def is_enabled(self): selection = self.view.sel()[0] return ( self.view.match_selector(selection.a, "text.git-blame") or self.view.match_selector(selection.a, "text.git-graph") )
mit
b0b71357be6d93aaae5921c9c1bc31a8
34.471429
194
0.580447
3.679881
false
false
false
false
posativ/isso
isso/__init__.py
1
10799
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2012-2014 Martin Zimmermann. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Isso – a lightweight Disqus alternative import pkg_resources dist = pkg_resources.get_distribution("isso") # check if exectuable is `isso` and gevent is available import sys if sys.argv[0].startswith("isso"): try: import gevent.monkey gevent.monkey.patch_all() except ImportError: pass import os import errno import logging import tempfile from os.path import abspath, dirname, exists, join from argparse import ArgumentParser from functools import partial, reduce from itsdangerous import URLSafeTimedSerializer from werkzeug.routing import Map from werkzeug.exceptions import HTTPException, InternalServerError from werkzeug.middleware.shared_data import SharedDataMiddleware from werkzeug.local import Local, LocalManager from werkzeug.serving import run_simple from werkzeug.middleware.proxy_fix import ProxyFix from werkzeug.middleware.profiler import ProfilerMiddleware local = Local() local_manager = LocalManager([local]) from isso import config, db, migrate, wsgi, ext, views from isso.core import ThreadedMixin, ProcessMixin, uWSGIMixin from isso.wsgi import origin, urlsplit from isso.utils import http, JSONRequest, JSONResponse, html, hash from isso.views import comments from isso.ext.notifications import Stdout, SMTP logging.getLogger('werkzeug').setLevel(logging.WARN) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s") logger = logging.getLogger("isso") def error_handler(env, request, error): if request.accept_mimetypes.best == "application/json": data = {'message': str(error)} code = 500 if error.code is None else error.code return JSONResponse(data, code) return error class ProxyFixCustom(ProxyFix): def __init__(self, app): # This is needed for werkzeug.wsgi.get_current_url called in isso/views/comments.py # to work properly when isso is hosted under a sub-path # cf. https://werkzeug.palletsprojects.com/en/1.0.x/middleware/proxy_fix/ super().__init__(app, x_prefix=1) class Isso(object): def __init__(self, conf): self.conf = conf self.db = db.SQLite3(conf.get('general', 'dbpath'), conf) self.signer = URLSafeTimedSerializer( self.db.preferences.get("session-key")) self.markup = html.Markup(conf.section('markup')) self.hasher = hash.new(conf.section("hash")) super(Isso, self).__init__(conf) subscribers = [] smtp_backend = False for backend in conf.getlist("general", "notify"): if backend == "stdout": subscribers.append(Stdout(None)) elif backend in ("smtp", "SMTP"): smtp_backend = True else: logger.warning("unknown notification backend '%s'", backend) if smtp_backend or conf.getboolean("general", "reply-notifications"): subscribers.append(SMTP(self)) self.signal = ext.Signal(*subscribers) self.urls = Map() views.Info(self) comments.API(self, self.hasher) def render(self, text): return self.markup.render(text) def sign(self, obj): return self.signer.dumps(obj) def unsign(self, obj, max_age=None): return self.signer.loads(obj, max_age=max_age or self.conf.getint('general', 'max-age')) def dispatch(self, request): local.request = request local.host = wsgi.host(request.environ) local.origin = origin(self.conf.getiter( "general", "host"))(request.environ) adapter = self.urls.bind_to_environ(request.environ) try: handler, values = adapter.match() except HTTPException as e: return error_handler(request.environ, request, e) else: try: response = handler(request.environ, request, **values) except HTTPException as e: return error_handler(request.environ, request, e) except Exception: logger.exception("%s %s", request.method, request.environ["PATH_INFO"]) return error_handler(request.environ, request, InternalServerError()) else: return response def wsgi_app(self, environ, start_response): response = self.dispatch(JSONRequest(environ)) return response(environ, start_response) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response) def make_app(conf=None, threading=True, multiprocessing=False, uwsgi=False): if not any((threading, multiprocessing, uwsgi)): raise RuntimeError("either set threading, multiprocessing or uwsgi") if threading: class App(Isso, ThreadedMixin): pass elif multiprocessing: class App(Isso, ProcessMixin): pass else: class App(Isso, uWSGIMixin): pass isso = App(conf) logger.info("Using database at '%s'", abspath(isso.conf.get('general', 'dbpath'))) if not any(conf.getiter("general", "host")): logger.error("No website(s) configured, Isso won't work.") sys.exit(1) # check HTTP server connection for host in conf.getiter("general", "host"): with http.curl('HEAD', host, '/', 5) as resp: if resp is not None: logger.info("connected to %s", host) break else: logger.warning("unable to connect to your website, Isso will probably not " "work correctly. Please make sure, Isso can reach your " "website via HTTP(S).") wrapper = [local_manager.make_middleware] if isso.conf.getboolean("server", "profile"): wrapper.append(partial(ProfilerMiddleware, sort_by=("cumulative", ), restrictions=("isso/(?!lib)", 10))) wrapper.append(partial(SharedDataMiddleware, exports={ '/js': join(dirname(__file__), 'js/'), '/css': join(dirname(__file__), 'css/'), '/img': join(dirname(__file__), 'img/'), '/demo': join(dirname(__file__), 'demo/') })) wrapper.append(partial(wsgi.CORSMiddleware, origin=origin(isso.conf.getiter("general", "host")), allowed=("Origin", "Referer", "Content-Type"), exposed=("X-Set-Cookie", "Date"))) wrapper.extend([wsgi.SubURI, ProxyFixCustom]) return reduce(lambda x, f: f(x), wrapper, isso) def main(): parser = ArgumentParser(description="a blog comment hosting service") subparser = parser.add_subparsers(help="commands", dest="command") parser.add_argument('--version', action='version', version='%(prog)s ' + dist.version) parser.add_argument("-c", dest="conf", default="/etc/isso.cfg", metavar="/etc/isso.cfg", help="set configuration file") imprt = subparser.add_parser('import', help="import Disqus XML export") imprt.add_argument("dump", metavar="FILE") imprt.add_argument("-n", "--dry-run", dest="dryrun", action="store_true", help="perform a trial run with no changes made") imprt.add_argument("-t", "--type", dest="type", default=None, choices=["disqus", "wordpress", "generic"], help="export type") imprt.add_argument("--empty-id", dest="empty_id", action="store_true", help="workaround for weird Disqus XML exports, #135") # run Isso as stand-alone server subparser.add_parser("run", help="run server") args = parser.parse_args() # ISSO_SETTINGS env var takes precedence over `-c` flag conf_file = os.environ.get('ISSO_SETTINGS') or args.conf if not conf_file: logger.error("No configuration file specified! Exiting.") sys.exit(1) if exists(conf_file): logger.info("Using configuration file '%s'", abspath(conf_file)) else: logger.error("Specified config '%s' does not exist! Exiting.", abspath(conf_file)) sys.exit(1) conf = config.load(config.default_file(), conf_file) if args.command == "import": conf.set("guard", "enabled", "off") if args.dryrun: xxx = tempfile.NamedTemporaryFile() dbpath = xxx.name else: dbpath = conf.get("general", "dbpath") mydb = db.SQLite3(dbpath, conf) migrate.dispatch(args.type, mydb, args.dump, args.empty_id) sys.exit(0) if conf.get("general", "log-file"): handler = logging.FileHandler(conf.get("general", "log-file")) logger.addHandler(handler) logging.getLogger("werkzeug").addHandler(handler) logger.propagate = False logging.getLogger("werkzeug").propagate = False if conf.get("server", "listen").startswith("http://"): host, port, _ = urlsplit(conf.get("server", "listen")) try: from gevent.pywsgi import WSGIServer WSGIServer((host, port), make_app(conf)).serve_forever() except ImportError: run_simple(host, port, make_app(conf), threaded=True, use_reloader=conf.getboolean('server', 'reload')) else: sock = conf.get("server", "listen").partition("unix://")[2] try: os.unlink(sock) except OSError as ex: if ex.errno != errno.ENOENT: raise wsgi.SocketHTTPServer(sock, make_app(conf)).serve_forever()
mit
9bb63da9c3a36162f0f465581575e42c
34.4
96
0.632027
4.072803
false
false
false
false
enkore/i3pystatus
i3pystatus/circleci.py
4
5445
import os import dateutil.parser from circleci.api import Api from i3pystatus import IntervalModule from i3pystatus.core.util import TimeWrapper, formatp, internet, require __author__ = 'chestm007' class CircleCI(IntervalModule): """ Get current status of circleci builds Requires `circleci` `dateutil.parser` Formatters: * `{repo_slug}` - repository owner/repository name * `{repo_status}` - repository status * `{repo_name}` - repository name * `{repo_owner}` - repository owner * `{last_build_started}` - date of the last finished started * `{last_build_duration}` - duration of the last build, not populated with workflows(yet) Examples .. code-block:: python status_color_map = { 'passed': '#00FF00', 'failed': '#FF0000', 'errored': '#FFAA00', 'cancelled': '#EEEEEE', 'started': '#0000AA', } .. code-block:: python repo_status_map={ 'success': '<span color="#00af00">success</span>', 'running': '<span color="#0000af">running</span>', 'failed': '<span color="#af0000">failed</span>', } """ settings = ( 'format', ('circleci_token', 'circleci access token'), ('repo_slug', 'repository identifier eg. "enkore/i3pystatus"'), ('time_format', 'passed directly to .strftime() for `last_build_started`'), ('repo_status_map', 'map representing how to display status'), ('duration_format', '`last_build_duration` format string'), ('status_color_map', 'color for all text based on status'), ('color', 'color for all text not otherwise colored'), ('workflow_name', '[WORKFLOWS_ONLY] if specified, monitor this workflows status. if not specified this module ' 'will default to reporting the status of your last build'), ('workflow_branch', '[WORKFLOWS_ONLY] if specified, monitor the workflows in this branch')) required = ('circleci_token', 'repo_slug') format = '{repo_owner}/{repo_name}-{repo_status} [({last_build_started}({last_build_duration}))]' short_format = '{repo_name}-{repo_status}' time_format = '%m/%d' duration_format = '%m:%S' status_color_map = None repo_slug = None circleci_token = None repo_status_map = None color = '#DDDDDD' workflow_name = None workflow_branch = None circleci = None on_leftclick = 'open_build_webpage' def init(self): self.repo_status = None self.last_build_duration = None self.last_build_started = None self.repo_owner, self.repo_name = self.repo_slug.split('/') self.workflows = self.workflow_name is not None or self.workflow_branch is not None def _format_time(self, time): _datetime = dateutil.parser.parse(time) return _datetime.strftime(self.time_format) @require(internet) def run(self): if self.circleci is None: self.circleci = Api(self.circleci_token) if self.workflows: if self.workflow_branch and not self.workflow_name: self.output = dict( full_text='workflow_name must be specified!' ) return project = {p['reponame']: p for p in self.circleci.get_projects()}.get(self.repo_name) if not self.workflow_branch: self.workflow_branch = project.get('default_branch') workflow_info = project['branches'].get(self.workflow_branch)['latest_workflows'].get(self.workflow_name) self.last_build_started = self._format_time(workflow_info.get('created_at')) self.repo_status = workflow_info.get('status') self.last_build_duration = '' # TODO: gather this information once circleCI exposes it else: self.repo_summary = self.circleci.get_project_build_summary( self.repo_owner, self.repo_name, limit=1) if len(self.repo_summary) != 1: return self.repo_summary = self.repo_summary[0] self.repo_status = self.repo_summary.get('status') self.last_build_started = self._format_time(self.repo_summary.get('queued_at')) try: self.last_build_duration = TimeWrapper( self.repo_summary.get('build_time_millis') / 1000, default_format=self.duration_format) except TypeError: self.last_build_duration = 0 if self.repo_status_map: self.repo_status = self.repo_status_map.get(self.repo_status, self.repo_status) self.output = dict( full_text=formatp(self.format, **vars(self)), short_text=self.short_format.format(**vars(self)), ) if self.status_color_map: self.output['color'] = self.status_color_map.get(self.repo_status, self.color) else: self.output['color'] = self.color def open_build_webpage(self): if self.repo_summary.get('workflows'): url_format = 'workflow-run/{}'.format(self.repo_summary['workflows']['workflow_id']) else: url_format = 'gh/{repo_owner}/{repo_name}/{job_number}' os.popen('xdg-open https:/circleci.com/{} > /dev/null' .format(url_format))
mit
d5b8a69ee9daca02b2f23b9617e6d86c
34.129032
119
0.590083
3.88651
false
false
false
false
warner/magic-wormhole
src/wormhole/_dilation/subchannel.py
1
14783
import six from collections import deque from attr import attrs, attrib from attr.validators import instance_of, provides from zope.interface import implementer from twisted.internet.defer import inlineCallbacks, returnValue from twisted.internet.interfaces import (ITransport, IProducer, IConsumer, IAddress, IListeningPort, IHalfCloseableProtocol, IStreamClientEndpoint, IStreamServerEndpoint) from twisted.internet.error import ConnectionDone from automat import MethodicalMachine from .._interfaces import ISubChannel, IDilationManager from ..observer import OneShotObserver # each subchannel frame (the data passed into transport.write(data)) gets a # 9-byte header prefix (type, subchannel id, and sequence number), then gets # encrypted (adding a 16-byte authentication tag). The result is transmitted # with a 4-byte length prefix (which only covers the padded message, not the # length prefix itself), so the padded message must be less than 2**32 bytes # long. MAX_FRAME_LENGTH = 2**32 - 1 - 9 - 16; @attrs class Once(object): _errtype = attrib() def __attrs_post_init__(self): self._called = False def __call__(self): if self._called: raise self._errtype() self._called = True class SingleUseEndpointError(Exception): pass # created in the (OPEN) state, by either: # * receipt of an OPEN message # * or local client_endpoint.connect() # then transitions are: # (OPEN) rx DATA: deliver .dataReceived(), -> (OPEN) # (OPEN) rx CLOSE: deliver .connectionLost(), send CLOSE, -> (CLOSED) # (OPEN) local .write(): send DATA, -> (OPEN) # (OPEN) local .loseConnection(): send CLOSE, -> (CLOSING) # (CLOSING) local .write(): error # (CLOSING) local .loseConnection(): error # (CLOSING) rx DATA: deliver .dataReceived(), -> (CLOSING) # (CLOSING) rx CLOSE: deliver .connectionLost(), -> (CLOSED) # object is deleted upon transition to (CLOSED) class AlreadyClosedError(Exception): pass class NormalCloseUsedOnHalfCloseable(Exception): pass class HalfCloseUsedOnNonHalfCloseable(Exception): pass @implementer(IAddress) class _WormholeAddress(object): pass @implementer(IAddress) @attrs class _SubchannelAddress(object): _scid = attrib(validator=instance_of(six.integer_types)) @attrs(eq=False) @implementer(ITransport) @implementer(IProducer) @implementer(IConsumer) @implementer(ISubChannel) class SubChannel(object): _scid = attrib(validator=instance_of(six.integer_types)) _manager = attrib(validator=provides(IDilationManager)) _host_addr = attrib(validator=instance_of(_WormholeAddress)) _peer_addr = attrib(validator=instance_of(_SubchannelAddress)) m = MethodicalMachine() set_trace = getattr(m, "_setTrace", lambda self, f: None) # pragma: no cover def __attrs_post_init__(self): # self._mailbox = None # self._pending_outbound = {} # self._processed = set() self._protocol = None self._pending_remote_data = [] self._pending_remote_close = False @m.state(initial=True) def unconnected(self): pass # pragma: no cover # once we get the IProtocol, it's either a IHalfCloseableProtocol, or it # can only be fully closed @m.state() def open_half(self): pass # pragma: no cover @m.state() def read_closed(): pass # pragma: no cover @m.state() def write_closed(): pass # pragma: no cover @m.state() def open_full(self): pass # pragma: no cover @m.state() def closing(): pass # pragma: no cover @m.state() def closed(): pass # pragma: no cover @m.input() def connect_protocol_half(self): pass @m.input() def connect_protocol_full(self): pass @m.input() def remote_data(self, data): pass @m.input() def remote_close(self): pass @m.input() def local_data(self, data): pass @m.input() def local_close(self): pass @m.output() def queue_remote_data(self, data): self._pending_remote_data.append(data) @m.output() def queue_remote_close(self): self._pending_remote_close = True @m.output() def send_data(self, data): self._manager.send_data(self._scid, data) @m.output() def send_close(self): self._manager.send_close(self._scid) @m.output() def signal_dataReceived(self, data): assert self._protocol self._protocol.dataReceived(data) @m.output() def signal_readConnectionLost(self): IHalfCloseableProtocol(self._protocol).readConnectionLost() @m.output() def signal_writeConnectionLost(self): IHalfCloseableProtocol(self._protocol).writeConnectionLost() @m.output() def signal_connectionLost(self): assert self._protocol self._protocol.connectionLost(ConnectionDone()) @m.output() def close_subchannel(self): self._manager.subchannel_closed(self._scid, self) # we're deleted momentarily @m.output() def error_closed_write(self, data): raise AlreadyClosedError("write not allowed on closed subchannel") @m.output() def error_closed_close(self): raise AlreadyClosedError( "loseConnection not allowed on closed subchannel") # stuff that arrives before we have a protocol connected unconnected.upon(remote_data, enter=unconnected, outputs=[queue_remote_data]) unconnected.upon(remote_close, enter=unconnected, outputs=[queue_remote_close]) # IHalfCloseableProtocol flow unconnected.upon(connect_protocol_half, enter=open_half, outputs=[]) open_half.upon(remote_data, enter=open_half, outputs=[signal_dataReceived]) open_half.upon(local_data, enter=open_half, outputs=[send_data]) # remote closes first open_half.upon(remote_close, enter=read_closed, outputs=[signal_readConnectionLost]) read_closed.upon(local_data, enter=read_closed, outputs=[send_data]) read_closed.upon(local_close, enter=closed, outputs=[send_close, close_subchannel, # TODO: eventual-signal this? signal_writeConnectionLost, ]) # local closes first open_half.upon(local_close, enter=write_closed, outputs=[signal_writeConnectionLost, send_close]) write_closed.upon(local_data, enter=write_closed, outputs=[error_closed_write]) write_closed.upon(remote_data, enter=write_closed, outputs=[signal_dataReceived]) write_closed.upon(remote_close, enter=closed, outputs=[close_subchannel, signal_readConnectionLost, ]) # error cases write_closed.upon(local_close, enter=write_closed, outputs=[error_closed_close]) # fully-closeable-only flow unconnected.upon(connect_protocol_full, enter=open_full, outputs=[]) open_full.upon(remote_data, enter=open_full, outputs=[signal_dataReceived]) open_full.upon(local_data, enter=open_full, outputs=[send_data]) open_full.upon(remote_close, enter=closed, outputs=[send_close, close_subchannel, signal_connectionLost]) open_full.upon(local_close, enter=closing, outputs=[send_close]) closing.upon(remote_data, enter=closing, outputs=[signal_dataReceived]) closing.upon(remote_close, enter=closed, outputs=[close_subchannel, signal_connectionLost]) # error cases # we won't ever see an OPEN, since L4 will log+ignore those for us closing.upon(local_data, enter=closing, outputs=[error_closed_write]) closing.upon(local_close, enter=closing, outputs=[error_closed_close]) # the CLOSED state won't ever see messages, since we'll be deleted # our endpoints use these def _set_protocol(self, protocol): assert not self._protocol self._protocol = protocol if IHalfCloseableProtocol.providedBy(protocol): self.connect_protocol_half() else: # move from UNCONNECTED to OPEN self.connect_protocol_full(); def _deliver_queued_data(self): for data in self._pending_remote_data: self.remote_data(data) del self._pending_remote_data if self._pending_remote_close: self.remote_close() del self._pending_remote_close # ITransport def write(self, data): assert isinstance(data, type(b"")) assert len(data) <= MAX_FRAME_LENGTH self.local_data(data) def writeSequence(self, iovec): self.write(b"".join(iovec)) def loseWriteConnection(self): if not IHalfCloseableProtocol.providedBy(self._protocol): # this is a clear error raise HalfCloseUsedOnNonHalfCloseable() self.local_close(); def loseConnection(self): # TODO: what happens if an IHalfCloseableProtocol calls normal # loseConnection()? I think we need to close the read side too. if IHalfCloseableProtocol.providedBy(self._protocol): # I don't know is correct, so avoid this for now raise NormalCloseUsedOnHalfCloseable() self.local_close() def getHost(self): # we define "host addr" as the overall wormhole return self._host_addr def getPeer(self): # and "peer addr" as the subchannel within that wormhole return self._peer_addr # IProducer: throttle inbound data (wormhole "up" to local app's Protocol) def stopProducing(self): self._manager.subchannel_stopProducing(self) def pauseProducing(self): self._manager.subchannel_pauseProducing(self) def resumeProducing(self): self._manager.subchannel_resumeProducing(self) # IConsumer: allow the wormhole to throttle outbound data (app->wormhole) def registerProducer(self, producer, streaming): self._manager.subchannel_registerProducer(self, producer, streaming) def unregisterProducer(self): self._manager.subchannel_unregisterProducer(self) @implementer(IStreamClientEndpoint) @attrs class ControlEndpoint(object): _peer_addr = attrib(validator=provides(IAddress)) _subchannel_zero = attrib(validator=provides(ISubChannel)) _eventual_queue = attrib(repr=False) _used = False def __attrs_post_init__(self): self._once = Once(SingleUseEndpointError) self._wait_for_main_channel = OneShotObserver(self._eventual_queue) # from manager def _main_channel_ready(self): self._wait_for_main_channel.fire(None) def _main_channel_failed(self, f): self._wait_for_main_channel.error(f) @inlineCallbacks def connect(self, protocolFactory): # return Deferred that fires with IProtocol or Failure(ConnectError) self._once() yield self._wait_for_main_channel.when_fired() p = protocolFactory.buildProtocol(self._peer_addr) self._subchannel_zero._set_protocol(p) # this sets p.transport and calls p.connectionMade() p.makeConnection(self._subchannel_zero) self._subchannel_zero._deliver_queued_data() returnValue(p) @implementer(IStreamClientEndpoint) @attrs class SubchannelConnectorEndpoint(object): _manager = attrib(validator=provides(IDilationManager)) _host_addr = attrib(validator=instance_of(_WormholeAddress)) _eventual_queue = attrib(repr=False) def __attrs_post_init__(self): self._connection_deferreds = deque() self._wait_for_main_channel = OneShotObserver(self._eventual_queue) def _main_channel_ready(self): self._wait_for_main_channel.fire(None) def _main_channel_failed(self, f): self._wait_for_main_channel.error(f) @inlineCallbacks def connect(self, protocolFactory): # return Deferred that fires with IProtocol or Failure(ConnectError) yield self._wait_for_main_channel.when_fired() scid = self._manager.allocate_subchannel_id() self._manager.send_open(scid) peer_addr = _SubchannelAddress(scid) # ? f.doStart() # ? f.startedConnecting(CONNECTOR) # ?? sc = SubChannel(scid, self._manager, self._host_addr, peer_addr) self._manager.subchannel_local_open(scid, sc) p = protocolFactory.buildProtocol(peer_addr) sc._set_protocol(p) p.makeConnection(sc) # set p.transport = sc and call connectionMade() returnValue(p) @implementer(IStreamServerEndpoint) @attrs class SubchannelListenerEndpoint(object): _manager = attrib(validator=provides(IDilationManager)) _host_addr = attrib(validator=provides(IAddress)) _eventual_queue = attrib(repr=False) def __attrs_post_init__(self): self._once = Once(SingleUseEndpointError) self._factory = None self._pending_opens = deque() self._wait_for_main_channel = OneShotObserver(self._eventual_queue) # from manager (actually Inbound) def _got_open(self, t, peer_addr): if self._factory: self._connect(t, peer_addr) else: self._pending_opens.append((t, peer_addr)) def _connect(self, t, peer_addr): p = self._factory.buildProtocol(peer_addr) t._set_protocol(p) p.makeConnection(t) t._deliver_queued_data() def _main_channel_ready(self): self._wait_for_main_channel.fire(None) def _main_channel_failed(self, f): self._wait_for_main_channel.error(f) # IStreamServerEndpoint @inlineCallbacks def listen(self, protocolFactory): self._once() yield self._wait_for_main_channel.when_fired() self._factory = protocolFactory while self._pending_opens: (t, peer_addr) = self._pending_opens.popleft() self._connect(t, peer_addr) lp = SubchannelListeningPort(self._host_addr) returnValue(lp) @implementer(IListeningPort) @attrs class SubchannelListeningPort(object): _host_addr = attrib(validator=provides(IAddress)) def startListening(self): pass def stopListening(self): # TODO pass def getHost(self): return self._host_addr
mit
df5d03242a31660f2a135b9ea16435fc
32.905963
88
0.639383
3.926428
false
false
false
false
posativ/isso
docs/_extensions/sphinx_reredirects/__init__.py
1
4953
# Imported from https://gitlab.com/documatt/sphinx-reredirects # 2021-02-03, commit 15da4697d14bb45c8d0b3586e66fa5df6319045d # # Copyright (c) 2020, documatt # BSD 3-Clause license import re from fnmatch import fnmatch from pathlib import Path from string import Template from typing import Dict, Mapping from sphinx.application import Sphinx from sphinx.util import logging OPTION_REDIRECTS = "redirects" OPTION_REDIRECTS_DEFAULT: Dict[str, str] = {} OPTION_TEMPLATE_FILE = "redirect_html_template_file" OPTION_TEMPLATE_FILE_DEFAULT = None REDIRECT_FILE_DEFAULT_TEMPLATE = '<html><head><meta http-equiv="refresh" content="0; url=${to_uri}"></head></html>' # noqa: E501 logger = logging.getLogger(__name__) wildcard_pattern = re.compile(r"[\*\?\[\]]") def setup(app: Sphinx): """ Extension setup, called by Sphinx """ app.connect("html-collect-pages", init) app.add_config_value(OPTION_REDIRECTS, OPTION_REDIRECTS_DEFAULT, "env") app.add_config_value(OPTION_TEMPLATE_FILE, OPTION_TEMPLATE_FILE_DEFAULT, "env") def init(app: Sphinx): if not app.config[OPTION_REDIRECTS]: logger.debug('No redirects configured') return rr = Reredirects(app) to_be_redirected = rr.grab_redirects() rr.create_redirects(to_be_redirected) # html-collect-pages requires to return iterable of pages to write, # we have no additional pages to write return [] class Reredirects: def __init__(self, app: Sphinx): self.app = app self.redirects_option: Dict[str, str] = getattr(app.config, OPTION_REDIRECTS) self.template_file_option: str = getattr(app.config, OPTION_TEMPLATE_FILE) def grab_redirects(self) -> Mapping[str, str]: """Inspect redirects option in conf.py and returns dict mapping \ docname to target (with expanded placeholder).""" # docname-target dict to_be_redirected = {} # For each source-target redirect pair in conf.py for source, target in self.redirects_option.items(): # no wildcard, append source as-is if not self._contains_wildcard(source): to_be_redirected[source] = target continue # wildcarded source, expand to docnames expanded_docs = [ doc for doc in self.app.env.found_docs if fnmatch(doc, source) ] if not expanded_docs: logger.warning(f"No documents match to '{source}' redirect.") continue for doc in expanded_docs: new_target = self._apply_placeholders(doc, target) to_be_redirected[doc] = new_target return to_be_redirected def create_redirects(self, to_be_redirected: Mapping[str, str]): """Create actual redirect file for each pair in passed mapping of \ docnames to targets.""" for doc, target in to_be_redirected.items(): redirect_file_abs = Path( self.app.outdir).joinpath(doc, "index.html") redirect_file_rel = redirect_file_abs.relative_to(self.app.outdir) if redirect_file_abs.exists(): logger.info(f"Creating redirect file '{redirect_file_rel}' " f"pointing to '{target}' that replaces " f"document '{doc}'.") else: logger.info(f"Creating redirect file '{redirect_file_rel}' " f"pointing to '{target}'.") self._create_redirect_file(redirect_file_abs, target) @staticmethod def _contains_wildcard(text): """Tells whether passed argument contains wildcard characters.""" return bool(wildcard_pattern.search(text)) @staticmethod def _apply_placeholders(source: str, target: str) -> str: """Expand "source" placeholder in target and return it""" return Template(target).substitute({"source": source}) def _create_redirect_file(self, at_path: Path, to_uri: str) -> None: """Actually create a redirect file according to redirect template""" content = self._render_redirect_template(to_uri) # create any missing parent folders at_path.parent.mkdir(parents=True, exist_ok=True) at_path.write_text(content) def _render_redirect_template(self, to_uri) -> str: # HTML used as redirect file content redirect_template = REDIRECT_FILE_DEFAULT_TEMPLATE if self.template_file_option: redirect_file_abs = Path(self.app.srcdir, self.template_file_option) redirect_template = redirect_file_abs.read_text() content = Template(redirect_template).substitute({"to_uri": to_uri}) return content
mit
7a8ee066165f7527ae2c236e46e15070
34.891304
129
0.611347
4.103563
false
false
false
false
warner/magic-wormhole
src/wormhole/_dilation/manager.py
1
24617
from __future__ import print_function, unicode_literals import six import os from collections import deque try: # py >= 3.3 from collections.abc import Sequence except ImportError: # py 2 and py3 < 3.3 from collections import Sequence from attr import attrs, attrib from attr.validators import provides, instance_of, optional from automat import MethodicalMachine from zope.interface import implementer from twisted.internet.defer import Deferred from twisted.internet.interfaces import (IStreamClientEndpoint, IStreamServerEndpoint) from twisted.python import log, failure from .._interfaces import IDilator, IDilationManager, ISend, ITerminator from ..util import dict_to_bytes, bytes_to_dict, bytes_to_hexstr from ..observer import OneShotObserver from .._key import derive_key from .subchannel import (SubChannel, _SubchannelAddress, _WormholeAddress, ControlEndpoint, SubchannelConnectorEndpoint, SubchannelListenerEndpoint) from .connector import Connector from .._hints import parse_hint from .roles import LEADER, FOLLOWER from .connection import KCM, Ping, Pong, Open, Data, Close, Ack from .inbound import Inbound from .outbound import Outbound # exported to Wormhole() for inclusion in versions message DILATION_VERSIONS = ["1"] class OldPeerCannotDilateError(Exception): pass class UnknownDilationMessageType(Exception): pass class ReceivedHintsTooEarly(Exception): pass class UnexpectedKCM(Exception): pass class UnknownMessageType(Exception): pass @attrs class EndpointRecord(Sequence): control = attrib(validator=provides(IStreamClientEndpoint)) connect = attrib(validator=provides(IStreamClientEndpoint)) listen = attrib(validator=provides(IStreamServerEndpoint)) def __len__(self): return 3 def __getitem__(self, n): return (self.control, self.connect, self.listen)[n] def make_side(): return bytes_to_hexstr(os.urandom(8)) # new scheme: # * both sides send PLEASE as soon as they have an unverified key and # w.dilate has been called, # * PLEASE includes a dilation-specific "side" (independent of the "side" # used by mailbox messages) # * higher "side" is Leader, lower is Follower # * PLEASE includes can-dilate list of version integers, requires overlap # "1" is current # * we start dilation after both w.dilate() and receiving VERSION, putting us # in WANTING, then we process all previously-queued inbound DILATE-n # messages. When PLEASE arrives, we move to CONNECTING # * HINTS sent after dilation starts # * only Leader sends RECONNECT, only Follower sends RECONNECTING. This # is the only difference between the two sides, and is not enforced # by the protocol (i.e. if the Follower sends RECONNECT to the Leader, # the Leader will obey, although TODO how confusing will this get?) # * upon receiving RECONNECT: drop Connector, start new Connector, send # RECONNECTING, start sending HINTS # * upon sending RECONNECT: go into FLUSHING state and ignore all HINTS until # RECONNECTING received. The new Connector can be spun up earlier, and it # can send HINTS, but it must not be given any HINTS that arrive before # RECONNECTING (since they're probably stale) # * after VERSIONS(KCM) received, we might learn that the other side cannot # dilate. w.dilate errbacks at this point # * maybe signal warning if we stay in a "want" state for too long # * nobody sends HINTS until they're ready to receive # * nobody sends HINTS unless they've called w.dilate() and received PLEASE # * nobody connects to inbound hints unless they've called w.dilate() # * if leader calls w.dilate() but not follower, leader waits forever in # "want" (doesn't send anything) # * if follower calls w.dilate() but not leader, follower waits forever # in "want", leader waits forever in "wanted" @attrs(eq=False) @implementer(IDilationManager) class Manager(object): _S = attrib(validator=provides(ISend), repr=False) _my_side = attrib(validator=instance_of(type(u""))) _transit_relay_location = attrib(validator=optional(instance_of(str))) _reactor = attrib(repr=False) _eventual_queue = attrib(repr=False) _cooperator = attrib(repr=False) # TODO: can this validator work when the parameter is optional? _no_listen = attrib(validator=instance_of(bool), default=False) _dilation_key = None _tor = None # TODO _timing = None # TODO _next_subchannel_id = None # initialized in choose_role m = MethodicalMachine() set_trace = getattr(m, "_setTrace", lambda self, f: None) # pragma: no cover def __attrs_post_init__(self): self._got_versions_d = Deferred() self._my_role = None # determined upon rx_PLEASE self._host_addr = _WormholeAddress() self._connection = None self._made_first_connection = False self._stopped = OneShotObserver(self._eventual_queue) self._debug_stall_connector = False self._next_dilation_phase = 0 # I kept getting confused about which methods were for inbound data # (and thus flow-control methods go "out") and which were for # outbound data (with flow-control going "in"), so I split them up # into separate pieces. self._inbound = Inbound(self, self._host_addr) self._outbound = Outbound(self, self._cooperator) # from us to peer # We must open subchannel0 early, since messages may arrive very # quickly once the connection is established. This subchannel may or # may not ever get revealed to the caller, since the peer might not # even be capable of dilation. scid0 = 0 peer_addr0 = _SubchannelAddress(scid0) sc0 = SubChannel(scid0, self, self._host_addr, peer_addr0) self._inbound.set_subchannel_zero(scid0, sc0) # we can open non-zero subchannels as soon as we get our first # connection, and we can make the Endpoints even earlier control_ep = ControlEndpoint(peer_addr0, sc0, self._eventual_queue) connect_ep = SubchannelConnectorEndpoint(self, self._host_addr, self._eventual_queue) listen_ep = SubchannelListenerEndpoint(self, self._host_addr, self._eventual_queue) # TODO: let inbound/outbound create the endpoints, then return them # to us self._inbound.set_listener_endpoint(listen_ep) self._endpoints = EndpointRecord(control_ep, connect_ep, listen_ep) def get_endpoints(self): return self._endpoints def got_dilation_key(self, key): assert isinstance(key, bytes) self._dilation_key = key def got_wormhole_versions(self, their_wormhole_versions): # this always happens before received_dilation_message dilation_version = None their_dilation_versions = set(their_wormhole_versions.get("can-dilate", [])) my_versions = set(DILATION_VERSIONS) shared_versions = my_versions.intersection(their_dilation_versions) if "1" in shared_versions: dilation_version = "1" # dilation_version is the best mutually-compatible version we have # with the peer, or None if we have nothing in common if not dilation_version: # "1" or None # TODO: be more specific about the error. dilation_version==None # means we had no version in common with them, which could either # be because they're so old they don't dilate at all, or because # they're so new that they no longer accommodate our old version self.fail(failure.Failure(OldPeerCannotDilateError())) self.start() def fail(self, f): self._endpoints.control._main_channel_failed(f) self._endpoints.connect._main_channel_failed(f) self._endpoints.listen._main_channel_failed(f) def received_dilation_message(self, plaintext): # this receives new in-order DILATE-n payloads, decrypted but not # de-JSONed. message = bytes_to_dict(plaintext) type = message["type"] if type == "please": self.rx_PLEASE(message) elif type == "connection-hints": self.rx_HINTS(message) elif type == "reconnect": self.rx_RECONNECT() elif type == "reconnecting": self.rx_RECONNECTING() else: log.err(UnknownDilationMessageType(message)) return def when_stopped(self): return self._stopped.when_fired() def send_dilation_phase(self, **fields): dilation_phase = self._next_dilation_phase self._next_dilation_phase += 1 self._S.send("dilate-%d" % dilation_phase, dict_to_bytes(fields)) def send_hints(self, hints): # from Connector self.send_dilation_phase(type="connection-hints", hints=hints) # forward inbound-ish things to _Inbound def subchannel_pauseProducing(self, sc): self._inbound.subchannel_pauseProducing(sc) def subchannel_resumeProducing(self, sc): self._inbound.subchannel_resumeProducing(sc) def subchannel_stopProducing(self, sc): self._inbound.subchannel_stopProducing(sc) def subchannel_local_open(self, scid, sc): self._inbound.subchannel_local_open(scid, sc) # forward outbound-ish things to _Outbound def subchannel_registerProducer(self, sc, producer, streaming): self._outbound.subchannel_registerProducer(sc, producer, streaming) def subchannel_unregisterProducer(self, sc): self._outbound.subchannel_unregisterProducer(sc) def send_open(self, scid): assert isinstance(scid, six.integer_types) self._queue_and_send(Open, scid) def send_data(self, scid, data): assert isinstance(scid, six.integer_types) self._queue_and_send(Data, scid, data) def send_close(self, scid): assert isinstance(scid, six.integer_types) self._queue_and_send(Close, scid) def _queue_and_send(self, record_type, *args): r = self._outbound.build_record(record_type, *args) # Outbound owns the send_record() pipe, so that it can stall new # writes after a new connection is made until after all queued # messages are written (to preserve ordering). self._outbound.queue_and_send_record(r) # may trigger pauseProducing def subchannel_closed(self, scid, sc): # let everyone clean up. This happens just after we delivered # connectionLost to the Protocol, except for the control channel, # which might get connectionLost later after they use ep.connect. # TODO: is this inversion a problem? self._inbound.subchannel_closed(scid, sc) self._outbound.subchannel_closed(scid, sc) # our Connector calls these def connector_connection_made(self, c): self.connection_made() # state machine update self._connection = c self._inbound.use_connection(c) self._outbound.use_connection(c) # does c.registerProducer if not self._made_first_connection: self._made_first_connection = True self._endpoints.control._main_channel_ready() self._endpoints.connect._main_channel_ready() self._endpoints.listen._main_channel_ready() pass def connector_connection_lost(self): self._stop_using_connection() if self._my_role is LEADER: self.connection_lost_leader() # state machine else: self.connection_lost_follower() def _stop_using_connection(self): # the connection is already lost by this point self._connection = None self._inbound.stop_using_connection() self._outbound.stop_using_connection() # does c.unregisterProducer # from our active Connection def got_record(self, r): # records with sequence numbers: always ack, ignore old ones if isinstance(r, (Open, Data, Close)): self.send_ack(r.seqnum) # always ack, even for old ones if self._inbound.is_record_old(r): return self._inbound.update_ack_watermark(r.seqnum) if isinstance(r, Open): self._inbound.handle_open(r.scid) elif isinstance(r, Data): self._inbound.handle_data(r.scid, r.data) else: # isinstance(r, Close) self._inbound.handle_close(r.scid) return if isinstance(r, KCM): log.err(UnexpectedKCM()) elif isinstance(r, Ping): self.handle_ping(r.ping_id) elif isinstance(r, Pong): self.handle_pong(r.ping_id) elif isinstance(r, Ack): self._outbound.handle_ack(r.resp_seqnum) # retire queued messages else: log.err(UnknownMessageType("{}".format(r))) # pings, pongs, and acks are not queued def send_ping(self, ping_id): self._outbound.send_if_connected(Ping(ping_id)) def send_pong(self, ping_id): self._outbound.send_if_connected(Pong(ping_id)) def send_ack(self, resp_seqnum): self._outbound.send_if_connected(Ack(resp_seqnum)) def handle_ping(self, ping_id): self.send_pong(ping_id) def handle_pong(self, ping_id): # TODO: update is-alive timer pass # subchannel maintenance def allocate_subchannel_id(self): scid_num = self._next_subchannel_id self._next_subchannel_id += 2 return scid_num # state machine @m.state(initial=True) def WAITING(self): pass # pragma: no cover @m.state() def WANTING(self): pass # pragma: no cover @m.state() def CONNECTING(self): pass # pragma: no cover @m.state() def CONNECTED(self): pass # pragma: no cover @m.state() def FLUSHING(self): pass # pragma: no cover @m.state() def ABANDONING(self): pass # pragma: no cover @m.state() def LONELY(self): pass # pragma: no cover @m.state() def STOPPING(self): pass # pragma: no cover @m.state(terminal=True) def STOPPED(self): pass # pragma: no cover @m.input() def start(self): pass # pragma: no cover @m.input() def rx_PLEASE(self, message): pass # pragma: no cover @m.input() # only sent by Follower def rx_HINTS(self, hint_message): pass # pragma: no cover @m.input() # only Leader sends RECONNECT, so only Follower receives it def rx_RECONNECT(self): pass # pragma: no cover @m.input() # only Follower sends RECONNECTING, so only Leader receives it def rx_RECONNECTING(self): pass # pragma: no cover # Connector gives us connection_made() @m.input() def connection_made(self): pass # pragma: no cover # our connection_lost() fires connection_lost_leader or # connection_lost_follower depending upon our role. If either side sees a # problem with the connection (timeouts, bad authentication) then they # just drop it and let connection_lost() handle the cleanup. @m.input() def connection_lost_leader(self): pass # pragma: no cover @m.input() def connection_lost_follower(self): pass @m.input() def stop(self): pass # pragma: no cover @m.output() def send_please(self): self.send_dilation_phase(type="please", side=self._my_side) @m.output() def choose_role(self, message): their_side = message["side"] if self._my_side > their_side: self._my_role = LEADER # scid 0 is reserved for the control channel. the leader uses odd # numbers starting with 1 self._next_subchannel_id = 1 elif their_side > self._my_side: self._my_role = FOLLOWER # the follower uses even numbers starting with 2 self._next_subchannel_id = 2 else: raise ValueError("their side shouldn't be equal: reflection?") # these Outputs behave differently for the Leader vs the Follower @m.output() def start_connecting_ignore_message(self, message): del message # ignored return self._start_connecting() @m.output() def start_connecting(self): self._start_connecting() def _start_connecting(self): assert self._my_role is not None assert self._dilation_key is not None self._connector = Connector(self._dilation_key, self._transit_relay_location, self, self._reactor, self._eventual_queue, self._no_listen, self._tor, self._timing, self._my_side, # needed for relay handshake self._my_role) if self._debug_stall_connector: # unit tests use this hook to send messages while we know we # don't have a connection self._eventual_queue.eventually(self._debug_stall_connector, self._connector) return self._connector.start() @m.output() def send_reconnect(self): self.send_dilation_phase(type="reconnect") # TODO: generation number? @m.output() def send_reconnecting(self): self.send_dilation_phase(type="reconnecting") # TODO: generation? @m.output() def use_hints(self, hint_message): hint_objs = filter(lambda h: h, # ignore None, unrecognizable [parse_hint(hs) for hs in hint_message["hints"]]) hint_objs = list(hint_objs) self._connector.got_hints(hint_objs) @m.output() def stop_connecting(self): self._connector.stop() @m.output() def abandon_connection(self): # we think we're still connected, but the Leader disagrees. Or we've # been told to shut down. self._connection.disconnect() # let connection_lost do cleanup @m.output() def notify_stopped(self): self._stopped.fire(None) # We are born WAITING after the local app calls w.dilate(). We enter # WANTING (and send a PLEASE) when we learn of a mutually-compatible # dilation_version. WAITING.upon(start, enter=WANTING, outputs=[send_please]) # we start CONNECTING when we get rx_PLEASE WANTING.upon(rx_PLEASE, enter=CONNECTING, outputs=[choose_role, start_connecting_ignore_message]) CONNECTING.upon(connection_made, enter=CONNECTED, outputs=[]) # Leader CONNECTED.upon(connection_lost_leader, enter=FLUSHING, outputs=[send_reconnect]) FLUSHING.upon(rx_RECONNECTING, enter=CONNECTING, outputs=[start_connecting]) # Follower # if we notice a lost connection, just wait for the Leader to notice too CONNECTED.upon(connection_lost_follower, enter=LONELY, outputs=[]) LONELY.upon(rx_RECONNECT, enter=CONNECTING, outputs=[send_reconnecting, start_connecting]) # but if they notice it first, abandon our (seemingly functional) # connection, then tell them that we're ready to try again CONNECTED.upon(rx_RECONNECT, enter=ABANDONING, outputs=[abandon_connection]) ABANDONING.upon(connection_lost_follower, enter=CONNECTING, outputs=[send_reconnecting, start_connecting]) # and if they notice a problem while we're still connecting, abandon our # incomplete attempt and try again. in this case we don't have to wait # for a connection to finish shutdown CONNECTING.upon(rx_RECONNECT, enter=CONNECTING, outputs=[stop_connecting, send_reconnecting, start_connecting]) # rx_HINTS never changes state, they're just accepted or ignored WANTING.upon(rx_HINTS, enter=WANTING, outputs=[]) # too early CONNECTING.upon(rx_HINTS, enter=CONNECTING, outputs=[use_hints]) CONNECTED.upon(rx_HINTS, enter=CONNECTED, outputs=[]) # too late, ignore FLUSHING.upon(rx_HINTS, enter=FLUSHING, outputs=[]) # stale, ignore LONELY.upon(rx_HINTS, enter=LONELY, outputs=[]) # stale, ignore ABANDONING.upon(rx_HINTS, enter=ABANDONING, outputs=[]) # shouldn't happen STOPPING.upon(rx_HINTS, enter=STOPPING, outputs=[]) WAITING.upon(stop, enter=STOPPED, outputs=[notify_stopped]) WANTING.upon(stop, enter=STOPPED, outputs=[notify_stopped]) CONNECTING.upon(stop, enter=STOPPED, outputs=[stop_connecting, notify_stopped]) CONNECTED.upon(stop, enter=STOPPING, outputs=[abandon_connection]) ABANDONING.upon(stop, enter=STOPPING, outputs=[]) FLUSHING.upon(stop, enter=STOPPED, outputs=[notify_stopped]) LONELY.upon(stop, enter=STOPPED, outputs=[notify_stopped]) STOPPING.upon(connection_lost_leader, enter=STOPPED, outputs=[notify_stopped]) STOPPING.upon(connection_lost_follower, enter=STOPPED, outputs=[notify_stopped]) @attrs @implementer(IDilator) class Dilator(object): """I launch the dilation process. I am created with every Wormhole (regardless of whether .dilate() was called or not), and I handle the initial phase of dilation, before we know whether we'll be the Leader or the Follower. Once we hear the other side's VERSION message (which tells us that we have a connection, they are capable of dilating, and which side we're on), then we build a Manager and hand control to it. """ _reactor = attrib() _eventual_queue = attrib() _cooperator = attrib() def __attrs_post_init__(self): self._manager = None self._pending_dilation_key = None self._pending_wormhole_versions = None self._pending_inbound_dilate_messages = deque() def wire(self, sender, terminator): self._S = ISend(sender) self._T = ITerminator(terminator) # this is the primary entry point, called when w.dilate() is invoked def dilate(self, transit_relay_location=None, no_listen=False): if not self._manager: # build the manager right away, and tell it later when the # VERSIONS message arrives, and also when the dilation_key is set my_dilation_side = make_side() m = Manager(self._S, my_dilation_side, transit_relay_location, self._reactor, self._eventual_queue, self._cooperator, no_listen) self._manager = m if self._pending_dilation_key is not None: m.got_dilation_key(self._pending_dilation_key) if self._pending_wormhole_versions: m.got_wormhole_versions(self._pending_wormhole_versions) while self._pending_inbound_dilate_messages: plaintext = self._pending_inbound_dilate_messages.popleft() m.received_dilation_message(plaintext) return self._manager.get_endpoints() # Called by Terminator after everything else (mailbox, nameplate, server # connection) has shut down. Expects to fire T.stoppedD() when Dilator is # stopped too. def stop(self): if self._manager: self._manager.stop() # TODO: avoid Deferreds for control flow, hard to serialize self._manager.when_stopped().addCallback(lambda _: self._T.stoppedD()) else: self._T.stoppedD() return # TODO: tolerate multiple calls # from Boss def got_key(self, key): # TODO: verify this happens before got_wormhole_versions, or add a gate # to tolerate either ordering purpose = b"dilation-v1" LENGTH = 32 # TODO: whatever Noise wants, I guess dilation_key = derive_key(key, purpose, LENGTH) if self._manager: self._manager.got_dilation_key(dilation_key) else: self._pending_dilation_key = dilation_key def got_wormhole_versions(self, their_wormhole_versions): if self._manager: self._manager.got_wormhole_versions(their_wormhole_versions) else: self._pending_wormhole_versions = their_wormhole_versions def received_dilate(self, plaintext): if not self._manager: self._pending_inbound_dilate_messages.append(plaintext) else: self._manager.received_dilation_message(plaintext)
mit
d428942e8ef61a591e62b6bfc4406a8c
36.930663
93
0.646829
3.814224
false
false
false
false
warner/magic-wormhole
src/wormhole/test/dilate/test_parse.py
1
2402
from __future__ import print_function, unicode_literals import mock from twisted.trial import unittest from ..._dilation.connection import (parse_record, encode_record, KCM, Ping, Pong, Open, Data, Close, Ack) class Parse(unittest.TestCase): def test_parse(self): self.assertEqual(parse_record(b"\x00"), KCM()) self.assertEqual(parse_record(b"\x01\x55\x44\x33\x22"), Ping(ping_id=b"\x55\x44\x33\x22")) self.assertEqual(parse_record(b"\x02\x55\x44\x33\x22"), Pong(ping_id=b"\x55\x44\x33\x22")) self.assertEqual(parse_record(b"\x03\x00\x00\x02\x01\x00\x00\x01\x00"), Open(scid=513, seqnum=256)) self.assertEqual(parse_record(b"\x04\x00\x00\x02\x02\x00\x00\x01\x01dataaa"), Data(scid=514, seqnum=257, data=b"dataaa")) self.assertEqual(parse_record(b"\x05\x00\x00\x02\x03\x00\x00\x01\x02"), Close(scid=515, seqnum=258)) self.assertEqual(parse_record(b"\x06\x00\x00\x01\x03"), Ack(resp_seqnum=259)) with mock.patch("wormhole._dilation.connection.log.err") as le: with self.assertRaises(ValueError): parse_record(b"\x07unknown") self.assertEqual(le.mock_calls, [mock.call("received unknown message type: {}".format( b"\x07unknown"))]) def test_encode(self): self.assertEqual(encode_record(KCM()), b"\x00") self.assertEqual(encode_record(Ping(ping_id=b"ping")), b"\x01ping") self.assertEqual(encode_record(Pong(ping_id=b"pong")), b"\x02pong") self.assertEqual(encode_record(Open(scid=65536, seqnum=16)), b"\x03\x00\x01\x00\x00\x00\x00\x00\x10") self.assertEqual(encode_record(Data(scid=65537, seqnum=17, data=b"dataaa")), b"\x04\x00\x01\x00\x01\x00\x00\x00\x11dataaa") self.assertEqual(encode_record(Close(scid=65538, seqnum=18)), b"\x05\x00\x01\x00\x02\x00\x00\x00\x12") self.assertEqual(encode_record(Ack(resp_seqnum=19)), b"\x06\x00\x00\x00\x13") with self.assertRaises(TypeError) as ar: encode_record("not a record") self.assertEqual(str(ar.exception), "not a record")
mit
0c9cb6c6da5230cf27f444a2fc41aed5
53.590909
85
0.579517
3.095361
false
true
false
false
posativ/isso
docs/conf.py
1
8361
# -*- coding: utf-8 -*- # # Isso documentation build configuration file, created by # sphinx-quickstart on Thu Nov 21 11:28:01 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import io import re import pkg_resources from os.path import dirname, join # Make `_theme` custom sphinx theme available sys.path.insert(0, join(dirname(__file__), "_theme/")) # Make `sphinx_reredirects` extension available sys.path.insert(0, join(dirname(__file__), "_extensions/")) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.todo', 'sphinx_reredirects', ] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # These patterns also affect html_static_path and html_extra_path exclude_patterns = [ "releasing.rst", ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # # The master toctree document. master_doc = 'docs/toc' # The document name of the “root” document, that is, the document that contains # the root toctree directive. Default is 'index'. # (Changed in version 4.0: Renamed root_doc from master_doc.) root_doc = 'docs/toc' # General information about the project. project = 'Isso' copyright = '2022, Martin Zimmermann & contributors' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. # See https://pygments.org/styles/ pygments_style = 'abap' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = '_theme' html_translator_class = "remove_heading.IssoTranslator" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { "collapse_navigation": False, "logo_only": True, "navigation_depth": 1, #"includehidden": False, #"titles_only": True, } # If true, the text around the keyword is shown as summary of each search result. # Default is True. html_show_search_summary = True # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["."] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = "_static/isso.svg" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'docs/**': ['sidebar-docs.html'], 'index': [], 'news': [], 'community': [], 'search': [], } # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {"index": "index.html"} # If false, no module index is generated. html_domain_indices = False # If false, no index is generated. html_use_index = False # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Issodoc' html_context = { 'display_github': True, 'github_user': 'posativ', 'github_repo': 'isso', 'github_version': 'master/docs/', } # -- Extension configuration ------------------------------------------------- # -- Options for todo extension ---------------------------------------------- # If true, `todo` and `todoList` produce output, else they produce nothing. # See https://sphinx-doc.org/en/master/usage/extensions/todo.html todo_include_todos = False # -- Options for reredirects extension ---------------------------------------------- redirects = { "contribute/": "/docs/contributing/", "docs/install/": "/docs/reference/installation/", "docs/quickstart/": "/docs/guides/quickstart/", "docs/troubleshooting/": "/docs/guides/troubleshooting/", "docs/setup/sub-uri/": "/docs/reference/multi-site-sub-uri/#sub-uri", "docs/setup/multiple-sites/": "/docs/reference/multi-site-sub-uri/#multiple-sites", "docs/configuration/server/": "/docs/reference/server-config/", "docs/configuration/client/": "/docs/reference/client-config/", "docs/extras/deployment/": "/docs/reference/deployment/", "docs/extras/advanced-integration/": "/docs/guides/advanced-integration/", "docs/extras/advanced-migration/": "/docs/guides/tips-and-tricks/#advanced-migration", "docs/extras/testing/": "/docs/technical-docs/testing/", "docs/extras/api/": "/docs/reference/server-api/", "docs/extras/contribs/": "/community/", }
mit
8eaf5b9ba95518895d05e9c561d01a99
34.261603
95
0.686012
3.764414
false
true
false
false
enkore/i3pystatus
i3pystatus/mem_bar.py
11
1772
from i3pystatus import IntervalModule from psutil import virtual_memory from i3pystatus.core.color import ColorRangeModule from i3pystatus.core.util import make_bar class MemBar(IntervalModule, ColorRangeModule): """ Shows memory load as a bar. .. rubric:: Available formatters * {used_mem_bar} Requires psutil and colour (from PyPI) """ format = "{used_mem_bar}" color = "#00FF00" warn_color = "#FFFF00" alert_color = "#FF0000" warn_percentage = 50 alert_percentage = 80 multi_colors = False def init(self): self.colors = self.get_hex_color_range(self.color, self.alert_color, 100) settings = ( ("format", "format string used for output."), ("warn_percentage", "minimal percentage for warn state"), ("alert_percentage", "minimal percentage for alert state"), ("color", "standard color"), ("warn_color", "defines the color used when warn percentage is exceeded"), ("alert_color", "defines the color used when alert percentage is exceeded"), ("multi_colors", "whether to use range of colors from 'color' to 'alert_color' based on memory usage."), ) def run(self): memory_usage = virtual_memory() if self.multi_colors: color = self.get_gradient(memory_usage.percent, self.colors) elif memory_usage.percent >= self.alert_percentage: color = self.alert_color elif memory_usage.percent >= self.warn_percentage: color = self.warn_color else: color = self.color self.output = { "full_text": self.format.format( used_mem_bar=make_bar(memory_usage.percent)), "color": color }
mit
cd1ec4bfaf99ba37bc0e10c10cb27d9d
30.087719
112
0.616817
4.073563
false
false
false
false
posativ/isso
isso/dispatch.py
1
1926
# -*- encoding: utf-8 -*- import sys import os import logging from glob import glob from werkzeug.middleware.dispatcher import DispatcherMiddleware from werkzeug.wrappers import Response from isso import make_app, wsgi, config logger = logging.getLogger("isso") class Dispatcher(DispatcherMiddleware): """ A dispatcher to support different websites. Dispatches based on a relative URI, e.g. /foo.example and /other.bar. """ def __init__(self, *confs): self.isso = {} default = config.default_file() for i, path in enumerate(confs): conf = config.load(default, path) if not conf.get("general", "name"): logger.warning("unable to dispatch %r, no 'name' set", confs[i]) continue self.isso["/" + conf.get("general", "name")] = make_app(conf) super(Dispatcher, self).__init__(self.default, mounts=self.isso) def __call__(self, environ, start_response): # clear X-Script-Name as the PATH_INFO is already adjusted environ.pop('HTTP_X_SCRIPT_NAME', None) return super(Dispatcher, self).__call__(environ, start_response) def default(self, environ, start_response): resp = Response("\n".join(self.isso.keys()), 404, content_type="text/plain") return resp(environ, start_response) settings = os.environ.get("ISSO_SETTINGS") if settings: if os.path.isdir(settings): conf_glob = os.path.join(settings, '*.cfg') confs = glob(conf_glob) application = wsgi.SubURI(Dispatcher(*confs)) else: confs = settings.split(";") for path in confs: if not os.path.isfile(path): logger.fatal("%s: no such file", path) sys.exit(1) application = wsgi.SubURI(Dispatcher(*confs)) else: logger.fatal('environment variable ISSO_SETTINGS must be set')
mit
cc7ff702493768b46cb3d4800ecd977a
28.630769
80
0.617342
3.844311
false
false
false
false
enkore/i3pystatus
i3pystatus/external_ip.py
11
2599
from i3pystatus import IntervalModule, formatp from i3pystatus.core.util import internet, require import GeoIP import urllib.request class ExternalIP(IntervalModule): """ Shows the external IP with the country code/name. Requires the PyPI package `GeoIP`. .. rubric:: Available formatters * {country_name} the full name of the country from the IP (eg. 'United States') * {country_code} the country code of the country from the IP (eg. 'US') * {ip} the ip """ interval = 15 settings = ( "format", "color", ("color_down", "color when the http request failed"), ("color_hide", "color when the user has decide to switch to the hide format"), ("format_down", "format when the http request failed"), ("format_hide", "format when the user has decide to switch to the hide format"), ("ip_website", "http website where the IP is directly available as raw"), ("timeout", "timeout in seconds when the http request is taking too much time"), ) format = "{country_name} {country_code} {ip}" format_hide = "{country_code}" format_down = "Timeout" ip_website = "https://api.ipify.org" timeout = 5 color = "#FFFFFF" color_hide = "#FFFF00" color_down = "#FF0000" on_leftclick = "switch_hide" on_rightclick = "run" @require(internet) def get_external_ip(self): try: request = urllib.request.urlopen(self.ip_website, timeout=self.timeout) return request.read().decode().strip() except Exception: return None def run(self): ip = self.get_external_ip() if not ip: return self.disable() gi = GeoIP.GeoIP(GeoIP.GEOIP_STANDARD) country_code = gi.country_code_by_addr(ip) country_name = gi.country_name_by_addr(ip) if not country_code: return self.disable() # fail here in the case of a bad IP fdict = { "country_name": country_name, "country_code": country_code, "ip": ip } self.output = { "full_text": formatp(self.format, **fdict).strip(), "color": self.color } def disable(self): self.output = { "full_text": self.format_down, "color": self.color_down } def switch_hide(self): self.format, self.format_hide = self.format_hide, self.format self.color, self.color_hide = self.color_hide, self.color self.run()
mit
2545ce0bf987f1b03010cee4f6c62c6b
28.873563
88
0.580993
3.931921
false
false
false
false
enkore/i3pystatus
i3pystatus/mpd.py
1
8097
from collections import defaultdict import socket from os.path import basename from math import floor from i3pystatus import IntervalModule, formatp from i3pystatus.core.util import TimeWrapper class MPD(IntervalModule): """ Displays various information from MPD (the music player daemon) .. rubric:: Available formatters (uses :ref:`formatp`) * `{title}` — (the title of the current song) * `{album}` — (the album of the current song, can be an empty string \ (e.g. for online streams)) * `{artist}` — (can be empty, too) * `{album_artist}` — (can be empty) * `{filename}` — (file name with out extension and path; empty unless \ title is empty) * `{song_elapsed}` — (Position in the currently playing song, uses \ :ref:`TimeWrapper`, default is `%m:%S`) * `{song_length}` — (Length of the current song, same as song_elapsed) * `{pos}` — (Position of current song in playlist, one-based) * `{len}` — (Songs in playlist) * `{status}` — (play, pause, stop mapped through the `status` dictionary) * `{bitrate}` — (Current bitrate in kilobit/s) * `{volume}` — (Volume set in MPD) .. rubric:: Available callbacks * ``switch_playpause`` — Plays if paused or stopped, otherwise pauses. \ Emulates ``mpc toggle``. * ``stop`` — Stops playback. Emulates ``mpc stop``. * ``next_song`` — Goes to next track in the playlist. Emulates ``mpc \ next``. * ``previous_song`` — Goes to previous track in the playlist. Emulates \ ``mpc prev``. * ``mpd_command`` — Send a command directly to MPD's socket. The command \ is the second element of the list. Documentation for available commands can \ be found at https://www.musicpd.org/doc/protocol/command_reference.html Example module registration with callbacks: :: status.register("mpd", on_leftclick="switch_playpause", on_rightclick=["mpd_command", "stop"], on_middleclick=["mpd_command", "shuffle"], on_upscroll=["mpd_command", "seekcur -10"], on_downscroll=["mpd_command", "seekcur +10"]) Note that ``next_song`` and ``previous_song``, and their ``mpd_command`` \ equivalents, are ignored while mpd is stopped. """ interval = 1 settings = ( ("host"), ("port", "MPD port. If set to 0, host will we interpreted as a Unix \ socket."), ("format", "formatp string"), ("status", "Dictionary mapping pause, play and stop to output"), ("color", "The color of the text"), ("color_map", "The mapping from state to color of the text"), ("max_field_len", "Defines max length for in truncate_fields defined \ fields, if truncated, ellipsis are appended as indicator. It's applied \ *before* max_len. Value of 0 disables this."), ("max_len", "Defines max length for the hole string, if exceeding \ fields specefied in truncate_fields are truncated equaly. If truncated, \ ellipsis are appended as indicator. It's applied *after* max_field_len. Value \ of 0 disables this."), ("time_format", "format string for 'pos' and 'len' fields"), ("truncate_fields", "fields that will be truncated if exceeding \ max_field_len or max_len."), ("hide_inactive", "Hides status information when MPD is not running"), ("password", "A password for access to MPD. (This is sent in \ cleartext to the server.)"), ) host = "localhost" port = 6600 password = None s = None format = "{title} {status}" status = { "pause": "▷", "play": "▶", "stop": "◾", } color = "#FFFFFF" color_map = {} max_field_len = 25 max_len = 100 time_format = "%m:%S" truncate_fields = ("title", "album", "artist", "album_artist") hide_inactive = False on_leftclick = "switch_playpause" on_rightclick = "next_song" on_upscroll = on_rightclick on_downscroll = "previous_song" def _mpd_command(self, sock, command): try: sock.send((command + "\n").encode("utf-8")) except Exception as e: if self.port != 0: self.s = socket.create_connection((self.host, self.port)) else: self.s = socket.socket(family=socket.AF_UNIX) self.s.connect(self.host) sock = self.s sock.recv(8192) if self.password is not None: sock.send('password "{}"\n'.format(self.password). encode("utf-8")) sock.recv(8192) sock.send((command + "\n").encode("utf-8")) try: reply = sock.recv(16384).decode("utf-8", "replace") replylines = reply.split("\n")[:-2] return dict( (line.split(": ", 1)) for line in replylines ) except Exception as e: return None def run(self): try: status = self._mpd_command(self.s, "status") playback_state = status["state"] if playback_state == "stop": currentsong = {} else: currentsong = self._mpd_command(self.s, "currentsong") or {} except Exception: if self.hide_inactive: self.output = { "full_text": "" } if hasattr(self, "data"): del self.data return fdict = { "pos": int(status.get("song", 0)) + 1, "len": int(status.get("playlistlength", 0)), "status": self.status[playback_state], "volume": int(status.get("volume", 0)), "title": currentsong.get("Title", ""), "album": currentsong.get("Album", ""), "artist": currentsong.get("Artist", ""), "album_artist": currentsong.get("AlbumArtist", ""), "song_length": TimeWrapper(currentsong.get("Time", 0), default_format=self.time_format), "song_elapsed": TimeWrapper(float(status.get("elapsed", 0)), default_format=self.time_format), "bitrate": int(status.get("bitrate", 0)), } if not fdict["title"] and "file" in currentsong: fdict["filename"] = '.'.join( basename(currentsong["file"]).split('.')[:-1]) else: fdict["filename"] = "" if self.max_field_len > 0: for key in self.truncate_fields: if len(fdict[key]) > self.max_field_len: fdict[key] = fdict[key][:self.max_field_len - 1] + "…" self.data = fdict full_text = formatp(self.format, **fdict).strip() full_text_len = len(full_text) if full_text_len > self.max_len and self.max_len > 0: shrink = floor((self.max_len - full_text_len) / len(self.truncate_fields)) - 1 for key in self.truncate_fields: fdict[key] = fdict[key][:shrink] + "…" full_text = formatp(self.format, **fdict).strip() color_map = defaultdict(lambda: self.color, self.color_map) self.output = { "full_text": full_text, "color": color_map[playback_state], } def switch_playpause(self): try: self._mpd_command(self.s, "play" if self._mpd_command(self.s, "status")["state"] in ["pause", "stop"] else "pause 1") except Exception as e: pass def stop(self): try: self._mpd_command(self.s, "stop") except Exception as e: pass def next_song(self): try: self._mpd_command(self.s, "next") except Exception as e: pass def previous_song(self): try: self._mpd_command(self.s, "previous") except Exception as e: pass def mpd_command(self, command): try: self._mpd_command(self.s, command) except Exception as e: pass
mit
16da4e3847d4cca40b5c7018a3073c9c
34.950893
106
0.55619
3.757816
false
false
false
false
warner/magic-wormhole
src/wormhole/test/test_machines.py
1
57816
from __future__ import print_function, unicode_literals import json from nacl.secret import SecretBox from spake2 import SPAKE2_Symmetric from twisted.trial import unittest from zope.interface import directlyProvides, implementer import mock from .. import (__version__, _allocator, _boss, _code, _input, _key, _lister, _mailbox, _nameplate, _order, _receive, _rendezvous, _send, _terminator, errors, timing) from .._interfaces import (IAllocator, IBoss, ICode, IDilator, IInput, IKey, ILister, IMailbox, INameplate, IOrder, IReceive, IRendezvousConnector, ISend, ITerminator, IWordlist, ITorManager) from .._key import derive_key, derive_phase_key, encrypt_data from ..journal import ImmediateJournal from ..util import (bytes_to_dict, bytes_to_hexstr, dict_to_bytes, hexstr_to_bytes, to_bytes) @implementer(IWordlist) class FakeWordList(object): def choose_words(self, length): return "-".join(["word"] * length) def get_completions(self, prefix): self._get_completions_prefix = prefix return self._completions class Dummy: def __init__(self, name, events, iface, *meths): self.name = name self.events = events if iface: directlyProvides(self, iface) for meth in meths: self.mock(meth) self.retval = None def mock(self, meth): def log(*args): self.events.append(("%s.%s" % (self.name, meth), ) + args) return self.retval setattr(self, meth, log) class Send(unittest.TestCase): def build(self): events = [] s = _send.Send(u"side", timing.DebugTiming()) m = Dummy("m", events, IMailbox, "add_message") s.wire(m) return s, m, events def test_send_first(self): s, m, events = self.build() s.send("phase1", b"msg") self.assertEqual(events, []) key = b"\x00" * 32 nonce1 = b"\x00" * SecretBox.NONCE_SIZE with mock.patch("nacl.utils.random", side_effect=[nonce1]) as r: s.got_verified_key(key) self.assertEqual(r.mock_calls, [mock.call(SecretBox.NONCE_SIZE)]) # print(bytes_to_hexstr(events[0][2])) enc1 = hexstr_to_bytes( ("000000000000000000000000000000000000000000000000" "22f1a46c3c3496423c394621a2a5a8cf275b08")) self.assertEqual(events, [("m.add_message", "phase1", enc1)]) events[:] = [] nonce2 = b"\x02" * SecretBox.NONCE_SIZE with mock.patch("nacl.utils.random", side_effect=[nonce2]) as r: s.send("phase2", b"msg") self.assertEqual(r.mock_calls, [mock.call(SecretBox.NONCE_SIZE)]) enc2 = hexstr_to_bytes( ("0202020202020202020202020202020202020202" "020202026660337c3eac6513c0dac9818b62ef16d9cd7e")) self.assertEqual(events, [("m.add_message", "phase2", enc2)]) def test_key_first(self): s, m, events = self.build() key = b"\x00" * 32 s.got_verified_key(key) self.assertEqual(events, []) nonce1 = b"\x00" * SecretBox.NONCE_SIZE with mock.patch("nacl.utils.random", side_effect=[nonce1]) as r: s.send("phase1", b"msg") self.assertEqual(r.mock_calls, [mock.call(SecretBox.NONCE_SIZE)]) enc1 = hexstr_to_bytes(("00000000000000000000000000000000000000000000" "000022f1a46c3c3496423c394621a2a5a8cf275b08")) self.assertEqual(events, [("m.add_message", "phase1", enc1)]) events[:] = [] nonce2 = b"\x02" * SecretBox.NONCE_SIZE with mock.patch("nacl.utils.random", side_effect=[nonce2]) as r: s.send("phase2", b"msg") self.assertEqual(r.mock_calls, [mock.call(SecretBox.NONCE_SIZE)]) enc2 = hexstr_to_bytes( ("0202020202020202020202020202020202020" "202020202026660337c3eac6513c0dac9818b62ef16d9cd7e")) self.assertEqual(events, [("m.add_message", "phase2", enc2)]) class Order(unittest.TestCase): def build(self): events = [] o = _order.Order(u"side", timing.DebugTiming()) k = Dummy("k", events, IKey, "got_pake") r = Dummy("r", events, IReceive, "got_message") o.wire(k, r) return o, k, r, events def test_in_order(self): o, k, r, events = self.build() o.got_message(u"side", u"pake", b"body") self.assertEqual(events, [("k.got_pake", b"body")]) # right away o.got_message(u"side", u"version", b"body") o.got_message(u"side", u"1", b"body") self.assertEqual(events, [ ("k.got_pake", b"body"), ("r.got_message", u"side", u"version", b"body"), ("r.got_message", u"side", u"1", b"body"), ]) def test_out_of_order(self): o, k, r, events = self.build() o.got_message(u"side", u"version", b"body") self.assertEqual(events, []) # nothing yet o.got_message(u"side", u"1", b"body") self.assertEqual(events, []) # nothing yet o.got_message(u"side", u"pake", b"body") # got_pake is delivered first self.assertEqual(events, [ ("k.got_pake", b"body"), ("r.got_message", u"side", u"version", b"body"), ("r.got_message", u"side", u"1", b"body"), ]) class Receive(unittest.TestCase): def build(self): events = [] r = _receive.Receive(u"side", timing.DebugTiming()) b = Dummy("b", events, IBoss, "happy", "scared", "got_verifier", "got_message") s = Dummy("s", events, ISend, "got_verified_key") r.wire(b, s) return r, b, s, events def test_good(self): r, b, s, events = self.build() key = b"key" r.got_key(key) self.assertEqual(events, []) verifier = derive_key(key, b"wormhole:verifier") phase1_key = derive_phase_key(key, u"side", u"phase1") data1 = b"data1" good_body = encrypt_data(phase1_key, data1) r.got_message(u"side", u"phase1", good_body) self.assertEqual(events, [ ("s.got_verified_key", key), ("b.happy", ), ("b.got_verifier", verifier), ("b.got_message", u"phase1", data1), ]) phase2_key = derive_phase_key(key, u"side", u"phase2") data2 = b"data2" good_body = encrypt_data(phase2_key, data2) r.got_message(u"side", u"phase2", good_body) self.assertEqual(events, [ ("s.got_verified_key", key), ("b.happy", ), ("b.got_verifier", verifier), ("b.got_message", u"phase1", data1), ("b.got_message", u"phase2", data2), ]) def test_early_bad(self): r, b, s, events = self.build() key = b"key" r.got_key(key) self.assertEqual(events, []) phase1_key = derive_phase_key(key, u"side", u"bad") data1 = b"data1" bad_body = encrypt_data(phase1_key, data1) r.got_message(u"side", u"phase1", bad_body) self.assertEqual(events, [ ("b.scared", ), ]) phase2_key = derive_phase_key(key, u"side", u"phase2") data2 = b"data2" good_body = encrypt_data(phase2_key, data2) r.got_message(u"side", u"phase2", good_body) self.assertEqual(events, [ ("b.scared", ), ]) def test_late_bad(self): r, b, s, events = self.build() key = b"key" r.got_key(key) self.assertEqual(events, []) verifier = derive_key(key, b"wormhole:verifier") phase1_key = derive_phase_key(key, u"side", u"phase1") data1 = b"data1" good_body = encrypt_data(phase1_key, data1) r.got_message(u"side", u"phase1", good_body) self.assertEqual(events, [ ("s.got_verified_key", key), ("b.happy", ), ("b.got_verifier", verifier), ("b.got_message", u"phase1", data1), ]) phase2_key = derive_phase_key(key, u"side", u"bad") data2 = b"data2" bad_body = encrypt_data(phase2_key, data2) r.got_message(u"side", u"phase2", bad_body) self.assertEqual(events, [ ("s.got_verified_key", key), ("b.happy", ), ("b.got_verifier", verifier), ("b.got_message", u"phase1", data1), ("b.scared", ), ]) r.got_message(u"side", u"phase1", good_body) r.got_message(u"side", u"phase2", bad_body) self.assertEqual(events, [ ("s.got_verified_key", key), ("b.happy", ), ("b.got_verifier", verifier), ("b.got_message", u"phase1", data1), ("b.scared", ), ]) class Key(unittest.TestCase): def build(self): events = [] k = _key.Key(u"appid", {}, u"side", timing.DebugTiming()) b = Dummy("b", events, IBoss, "scared", "got_key") m = Dummy("m", events, IMailbox, "add_message") r = Dummy("r", events, IReceive, "got_key") k.wire(b, m, r) return k, b, m, r, events def test_good(self): k, b, m, r, events = self.build() code = u"1-foo" k.got_code(code) self.assertEqual(len(events), 1) self.assertEqual(events[0][:2], ("m.add_message", "pake")) msg1_json = events[0][2].decode("utf-8") events[:] = [] msg1 = json.loads(msg1_json) msg1_bytes = hexstr_to_bytes(msg1["pake_v1"]) sp = SPAKE2_Symmetric(to_bytes(code), idSymmetric=to_bytes(u"appid")) msg2_bytes = sp.start() key2 = sp.finish(msg1_bytes) msg2 = dict_to_bytes({"pake_v1": bytes_to_hexstr(msg2_bytes)}) k.got_pake(msg2) self.assertEqual(len(events), 3, events) self.assertEqual(events[0], ("b.got_key", key2)) self.assertEqual(events[1][:2], ("m.add_message", "version")) self.assertEqual(events[2], ("r.got_key", key2)) def test_bad(self): k, b, m, r, events = self.build() code = u"1-foo" k.got_code(code) self.assertEqual(len(events), 1) self.assertEqual(events[0][:2], ("m.add_message", "pake")) pake_1_json = events[0][2].decode("utf-8") pake_1 = json.loads(pake_1_json) self.assertEqual(list(pake_1.keys()), ["pake_v1"]) # value is PAKE stuff events[:] = [] bad_pake_d = {"not_pake_v1": "stuff"} k.got_pake(dict_to_bytes(bad_pake_d)) self.assertEqual(events, [("b.scared", )]) def test_reversed(self): # A receiver using input_code() will choose the nameplate first, then # the rest of the code. Once the nameplate is selected, we'll claim # it and open the mailbox, which will cause the senders PAKE to # arrive before the code has been set. Key() is supposed to stash the # PAKE message until the code is set (allowing the PAKE computation # to finish). This test exercises that PAKE-then-code sequence. k, b, m, r, events = self.build() code = u"1-foo" sp = SPAKE2_Symmetric(to_bytes(code), idSymmetric=to_bytes(u"appid")) msg2_bytes = sp.start() msg2 = dict_to_bytes({"pake_v1": bytes_to_hexstr(msg2_bytes)}) k.got_pake(msg2) self.assertEqual(len(events), 0) k.got_code(code) self.assertEqual(len(events), 4) self.assertEqual(events[0][:2], ("m.add_message", "pake")) msg1_json = events[0][2].decode("utf-8") msg1 = json.loads(msg1_json) msg1_bytes = hexstr_to_bytes(msg1["pake_v1"]) key2 = sp.finish(msg1_bytes) self.assertEqual(events[1], ("b.got_key", key2)) self.assertEqual(events[2][:2], ("m.add_message", "version")) self.assertEqual(events[3], ("r.got_key", key2)) class Code(unittest.TestCase): def build(self): events = [] c = _code.Code(timing.DebugTiming()) b = Dummy("b", events, IBoss, "got_code") a = Dummy("a", events, IAllocator, "allocate") n = Dummy("n", events, INameplate, "set_nameplate") k = Dummy("k", events, IKey, "got_code") i = Dummy("i", events, IInput, "start") c.wire(b, a, n, k, i) return c, b, a, n, k, i, events def test_set_code(self): c, b, a, n, k, i, events = self.build() c.set_code(u"1-code") self.assertEqual(events, [ ("n.set_nameplate", u"1"), ("b.got_code", u"1-code"), ("k.got_code", u"1-code"), ]) def test_set_code_invalid(self): c, b, a, n, k, i, events = self.build() with self.assertRaises(errors.KeyFormatError) as e: c.set_code(u"1-code ") self.assertEqual(str(e.exception), "Code '1-code ' contains spaces.") with self.assertRaises(errors.KeyFormatError) as e: c.set_code(u" 1-code") self.assertEqual(str(e.exception), "Code ' 1-code' contains spaces.") with self.assertRaises(errors.KeyFormatError) as e: c.set_code(u"code-code") self.assertEqual( str(e.exception), "Nameplate 'code' must be numeric, with no spaces.") # it should still be possible to use the wormhole at this point c.set_code(u"1-code") self.assertEqual(events, [ ("n.set_nameplate", u"1"), ("b.got_code", u"1-code"), ("k.got_code", u"1-code"), ]) def test_allocate_code(self): c, b, a, n, k, i, events = self.build() wl = FakeWordList() c.allocate_code(2, wl) self.assertEqual(events, [("a.allocate", 2, wl)]) events[:] = [] c.allocated("1", "1-code") self.assertEqual(events, [ ("n.set_nameplate", u"1"), ("b.got_code", u"1-code"), ("k.got_code", u"1-code"), ]) def test_input_code(self): c, b, a, n, k, i, events = self.build() c.input_code() self.assertEqual(events, [("i.start", )]) events[:] = [] c.got_nameplate("1") self.assertEqual(events, [ ("n.set_nameplate", u"1"), ]) events[:] = [] c.finished_input("1-code") self.assertEqual(events, [ ("b.got_code", u"1-code"), ("k.got_code", u"1-code"), ]) class Input(unittest.TestCase): def build(self): events = [] i = _input.Input(timing.DebugTiming()) c = Dummy("c", events, ICode, "got_nameplate", "finished_input") l = Dummy("l", events, ILister, "refresh") i.wire(c, l) return i, c, l, events def test_ignore_completion(self): i, c, l, events = self.build() helper = i.start() self.assertIsInstance(helper, _input.Helper) self.assertEqual(events, [("l.refresh", )]) events[:] = [] with self.assertRaises(errors.MustChooseNameplateFirstError): helper.choose_words("word-word") helper.choose_nameplate("1") self.assertEqual(events, [("c.got_nameplate", "1")]) events[:] = [] with self.assertRaises(errors.AlreadyChoseNameplateError): helper.choose_nameplate("2") helper.choose_words("word-word") with self.assertRaises(errors.AlreadyChoseWordsError): helper.choose_words("word-word") self.assertEqual(events, [("c.finished_input", "1-word-word")]) def test_bad_nameplate(self): i, c, l, events = self.build() helper = i.start() self.assertIsInstance(helper, _input.Helper) self.assertEqual(events, [("l.refresh", )]) events[:] = [] with self.assertRaises(errors.MustChooseNameplateFirstError): helper.choose_words("word-word") with self.assertRaises(errors.KeyFormatError): helper.choose_nameplate(" 1") # should still work afterwards helper.choose_nameplate("1") self.assertEqual(events, [("c.got_nameplate", "1")]) events[:] = [] with self.assertRaises(errors.AlreadyChoseNameplateError): helper.choose_nameplate("2") helper.choose_words("word-word") with self.assertRaises(errors.AlreadyChoseWordsError): helper.choose_words("word-word") self.assertEqual(events, [("c.finished_input", "1-word-word")]) def test_with_completion(self): i, c, l, events = self.build() helper = i.start() self.assertIsInstance(helper, _input.Helper) self.assertEqual(events, [("l.refresh", )]) events[:] = [] d = helper.when_wordlist_is_available() self.assertNoResult(d) helper.refresh_nameplates() self.assertEqual(events, [("l.refresh", )]) events[:] = [] with self.assertRaises(errors.MustChooseNameplateFirstError): helper.get_word_completions("prefix") i.got_nameplates({"1", "12", "34", "35", "367"}) self.assertNoResult(d) self.assertEqual( helper.get_nameplate_completions(""), {"1-", "12-", "34-", "35-", "367-"}) self.assertEqual(helper.get_nameplate_completions("1"), {"1-", "12-"}) self.assertEqual(helper.get_nameplate_completions("2"), set()) self.assertEqual( helper.get_nameplate_completions("3"), {"34-", "35-", "367-"}) helper.choose_nameplate("34") with self.assertRaises(errors.AlreadyChoseNameplateError): helper.refresh_nameplates() with self.assertRaises(errors.AlreadyChoseNameplateError): helper.get_nameplate_completions("1") self.assertEqual(events, [("c.got_nameplate", "34")]) events[:] = [] # no wordlist yet self.assertNoResult(d) self.assertEqual(helper.get_word_completions(""), set()) wl = FakeWordList() i.got_wordlist(wl) self.assertEqual(self.successResultOf(d), None) # a new Deferred should fire right away d = helper.when_wordlist_is_available() self.assertEqual(self.successResultOf(d), None) wl._completions = {"abc-", "abcd-", "ae-"} self.assertEqual(helper.get_word_completions("a"), wl._completions) self.assertEqual(wl._get_completions_prefix, "a") with self.assertRaises(errors.AlreadyChoseNameplateError): helper.refresh_nameplates() with self.assertRaises(errors.AlreadyChoseNameplateError): helper.get_nameplate_completions("1") helper.choose_words("word-word") with self.assertRaises(errors.AlreadyChoseWordsError): helper.get_word_completions("prefix") with self.assertRaises(errors.AlreadyChoseWordsError): helper.choose_words("word-word") self.assertEqual(events, [("c.finished_input", "34-word-word")]) class Lister(unittest.TestCase): def build(self): events = [] lister = _lister.Lister(timing.DebugTiming()) rc = Dummy("rc", events, IRendezvousConnector, "tx_list") i = Dummy("i", events, IInput, "got_nameplates") lister.wire(rc, i) return lister, rc, i, events def test_connect_first(self): l, rc, i, events = self.build() l.connected() l.lost() l.connected() self.assertEqual(events, []) l.refresh() self.assertEqual(events, [ ("rc.tx_list", ), ]) events[:] = [] l.rx_nameplates({"1", "2", "3"}) self.assertEqual(events, [ ("i.got_nameplates", {"1", "2", "3"}), ]) events[:] = [] # now we're satisfied: disconnecting and reconnecting won't ask again l.lost() l.connected() self.assertEqual(events, []) # but if we're told to refresh, we'll do so l.refresh() self.assertEqual(events, [ ("rc.tx_list", ), ]) def test_connect_first_ask_twice(self): l, rc, i, events = self.build() l.connected() self.assertEqual(events, []) l.refresh() l.refresh() self.assertEqual(events, [ ("rc.tx_list", ), ("rc.tx_list", ), ]) l.rx_nameplates({"1", "2", "3"}) self.assertEqual(events, [ ("rc.tx_list", ), ("rc.tx_list", ), ("i.got_nameplates", {"1", "2", "3"}), ]) l.rx_nameplates({"1", "2", "3", "4"}) self.assertEqual(events, [ ("rc.tx_list", ), ("rc.tx_list", ), ("i.got_nameplates", {"1", "2", "3"}), ("i.got_nameplates", {"1", "2", "3", "4"}), ]) def test_reconnect(self): l, rc, i, events = self.build() l.refresh() l.connected() self.assertEqual(events, [ ("rc.tx_list", ), ]) events[:] = [] l.lost() l.connected() self.assertEqual(events, [ ("rc.tx_list", ), ]) def test_refresh_first(self): l, rc, i, events = self.build() l.refresh() self.assertEqual(events, []) l.connected() self.assertEqual(events, [ ("rc.tx_list", ), ]) l.rx_nameplates({"1", "2", "3"}) self.assertEqual(events, [ ("rc.tx_list", ), ("i.got_nameplates", {"1", "2", "3"}), ]) def test_unrefreshed(self): l, rc, i, events = self.build() self.assertEqual(events, []) # we receive a spontaneous rx_nameplates, without asking l.connected() self.assertEqual(events, []) l.rx_nameplates({"1", "2", "3"}) self.assertEqual(events, [ ("i.got_nameplates", {"1", "2", "3"}), ]) class Allocator(unittest.TestCase): def build(self): events = [] a = _allocator.Allocator(timing.DebugTiming()) rc = Dummy("rc", events, IRendezvousConnector, "tx_allocate") c = Dummy("c", events, ICode, "allocated") a.wire(rc, c) return a, rc, c, events def test_no_allocation(self): a, rc, c, events = self.build() a.connected() self.assertEqual(events, []) def test_allocate_first(self): a, rc, c, events = self.build() a.allocate(2, FakeWordList()) self.assertEqual(events, []) a.connected() self.assertEqual(events, [("rc.tx_allocate", )]) events[:] = [] a.lost() a.connected() self.assertEqual(events, [ ("rc.tx_allocate", ), ]) events[:] = [] a.rx_allocated("1") self.assertEqual(events, [ ("c.allocated", "1", "1-word-word"), ]) def test_connect_first(self): a, rc, c, events = self.build() a.connected() self.assertEqual(events, []) a.allocate(2, FakeWordList()) self.assertEqual(events, [("rc.tx_allocate", )]) events[:] = [] a.lost() a.connected() self.assertEqual(events, [ ("rc.tx_allocate", ), ]) events[:] = [] a.rx_allocated("1") self.assertEqual(events, [ ("c.allocated", "1", "1-word-word"), ]) class Nameplate(unittest.TestCase): def build(self): events = [] n = _nameplate.Nameplate() m = Dummy("m", events, IMailbox, "got_mailbox") i = Dummy("i", events, IInput, "got_wordlist") rc = Dummy("rc", events, IRendezvousConnector, "tx_claim", "tx_release") t = Dummy("t", events, ITerminator, "nameplate_done") n.wire(m, i, rc, t) return n, m, i, rc, t, events def test_set_invalid(self): n, m, i, rc, t, events = self.build() with self.assertRaises(errors.KeyFormatError) as e: n.set_nameplate(" 1") self.assertEqual( str(e.exception), "Nameplate ' 1' must be numeric, with no spaces.") with self.assertRaises(errors.KeyFormatError) as e: n.set_nameplate("one") self.assertEqual( str(e.exception), "Nameplate 'one' must be numeric, with no spaces.") # wormhole should still be usable n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) def test_set_first(self): # connection remains up throughout n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_connect_first(self): # connection remains up throughout n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_reconnect_while_claiming(self): # connection bounced while waiting for rx_claimed n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] n.lost() n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) def test_reconnect_while_claimed(self): # connection bounced while claimed: no retransmits should be sent n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.lost() n.connected() self.assertEqual(events, []) def test_reconnect_while_releasing(self): # connection bounced while waiting for rx_released n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.lost() n.connected() self.assertEqual(events, [("rc.tx_release", "1")]) def test_reconnect_while_done(self): # connection bounces after we're done n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) events[:] = [] n.lost() n.connected() self.assertEqual(events, []) def test_close_while_idle(self): n, m, i, rc, t, events = self.build() n.close() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_idle_connected(self): n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.close() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_unclaimed(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") n.close() # before ever being connected self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_claiming(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] n.close() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_claiming_but_disconnected(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] n.lost() n.close() self.assertEqual(events, []) # we're now waiting for a connection, so we can release the nameplate n.connected() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_claimed(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.close() # this path behaves just like a deliberate release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_claimed_but_disconnected(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.lost() n.close() # we're now waiting for a connection, so we can release the nameplate n.connected() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_releasing(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.close() # ignored, we're already on our way out the door self.assertEqual(events, []) n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_releasing_but_disconnecteda(self): n, m, i, rc, t, events = self.build() n.set_nameplate("1") self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.lost() n.close() # we must retransmit the tx_release when we reconnect self.assertEqual(events, []) n.connected() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) def test_close_while_done(self): # connection remains up throughout n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) events[:] = [] n.close() # NOP self.assertEqual(events, []) def test_close_while_done_but_disconnected(self): # connection remains up throughout n, m, i, rc, t, events = self.build() n.connected() self.assertEqual(events, []) n.set_nameplate("1") self.assertEqual(events, [("rc.tx_claim", "1")]) events[:] = [] wl = object() with mock.patch("wormhole._nameplate.PGPWordList", return_value=wl): n.rx_claimed("mbox1") self.assertEqual(events, [ ("i.got_wordlist", wl), ("m.got_mailbox", "mbox1"), ]) events[:] = [] n.release() self.assertEqual(events, [("rc.tx_release", "1")]) events[:] = [] n.rx_released() self.assertEqual(events, [("t.nameplate_done", )]) events[:] = [] n.lost() n.close() # NOP self.assertEqual(events, []) class Mailbox(unittest.TestCase): def build(self): events = [] m = _mailbox.Mailbox("side1") n = Dummy("n", events, INameplate, "release") rc = Dummy("rc", events, IRendezvousConnector, "tx_add", "tx_open", "tx_close") o = Dummy("o", events, IOrder, "got_message") t = Dummy("t", events, ITerminator, "mailbox_done") m.wire(n, rc, o, t) return m, n, rc, o, t, events # TODO: test moods def assert_events(self, events, initial_events, tx_add_events): self.assertEqual( len(events), len(initial_events) + len(tx_add_events), events) self.assertEqual(events[:len(initial_events)], initial_events) self.assertEqual(set(events[len(initial_events):]), tx_add_events) def test_connect_first(self): # connect before got_mailbox m, n, rc, o, t, events = self.build() m.add_message("phase1", b"msg1") self.assertEqual(events, []) m.connected() self.assertEqual(events, []) m.got_mailbox("mbox1") self.assertEqual(events, [("rc.tx_open", "mbox1"), ("rc.tx_add", "phase1", b"msg1")]) events[:] = [] m.add_message("phase2", b"msg2") self.assertEqual(events, [("rc.tx_add", "phase2", b"msg2")]) events[:] = [] # bouncing the connection should retransmit everything, even the open() m.lost() self.assertEqual(events, []) # and messages sent while here should be queued m.add_message("phase3", b"msg3") self.assertEqual(events, []) m.connected() # the other messages are allowed to be sent in any order self.assert_events( events, [("rc.tx_open", "mbox1")], { ("rc.tx_add", "phase1", b"msg1"), ("rc.tx_add", "phase2", b"msg2"), ("rc.tx_add", "phase3", b"msg3"), }) events[:] = [] m.rx_message("side1", "phase1", b"msg1") # echo of our message, dequeue self.assertEqual(events, []) m.lost() m.connected() self.assert_events(events, [("rc.tx_open", "mbox1")], { ("rc.tx_add", "phase2", b"msg2"), ("rc.tx_add", "phase3", b"msg3"), }) events[:] = [] # a new message from the peer gets delivered, and the Nameplate is # released since the message proves that our peer opened the Mailbox # and therefore no longer needs the Nameplate m.rx_message("side2", "phase1", b"msg1them") # new message from peer self.assertEqual(events, [ ("n.release", ), ("o.got_message", "side2", "phase1", b"msg1them"), ]) events[:] = [] # we de-duplicate peer messages, but still re-release the nameplate # since Nameplate is smart enough to ignore that m.rx_message("side2", "phase1", b"msg1them") self.assertEqual(events, [ ("n.release", ), ]) events[:] = [] m.close("happy") self.assertEqual(events, [("rc.tx_close", "mbox1", "happy")]) events[:] = [] # while closing, we ignore a lot m.add_message("phase-late", b"late") m.rx_message("side1", "phase2", b"msg2") m.close("happy") self.assertEqual(events, []) # bouncing the connection forces a retransmit of the tx_close m.lost() self.assertEqual(events, []) m.connected() self.assertEqual(events, [("rc.tx_close", "mbox1", "happy")]) events[:] = [] m.rx_closed() self.assertEqual(events, [("t.mailbox_done", )]) events[:] = [] # while closed, we ignore everything m.add_message("phase-late", b"late") m.rx_message("side1", "phase2", b"msg2") m.close("happy") m.lost() m.connected() self.assertEqual(events, []) def test_mailbox_first(self): # got_mailbox before connect m, n, rc, o, t, events = self.build() m.add_message("phase1", b"msg1") self.assertEqual(events, []) m.got_mailbox("mbox1") m.add_message("phase2", b"msg2") self.assertEqual(events, []) m.connected() self.assert_events(events, [("rc.tx_open", "mbox1")], { ("rc.tx_add", "phase1", b"msg1"), ("rc.tx_add", "phase2", b"msg2"), }) def test_close_while_idle(self): m, n, rc, o, t, events = self.build() m.close("happy") self.assertEqual(events, [("t.mailbox_done", )]) def test_close_while_idle_but_connected(self): m, n, rc, o, t, events = self.build() m.connected() m.close("happy") self.assertEqual(events, [("t.mailbox_done", )]) def test_close_while_mailbox_disconnected(self): m, n, rc, o, t, events = self.build() m.got_mailbox("mbox1") m.close("happy") self.assertEqual(events, [("t.mailbox_done", )]) def test_close_while_reconnecting(self): m, n, rc, o, t, events = self.build() m.got_mailbox("mbox1") m.connected() self.assertEqual(events, [("rc.tx_open", "mbox1")]) events[:] = [] m.lost() self.assertEqual(events, []) m.close("happy") self.assertEqual(events, []) # we now wait to connect, so we can send the tx_close m.connected() self.assertEqual(events, [("rc.tx_close", "mbox1", "happy")]) events[:] = [] m.rx_closed() self.assertEqual(events, [("t.mailbox_done", )]) events[:] = [] class Terminator(unittest.TestCase): def build(self): events = [] t = _terminator.Terminator() b = Dummy("b", events, IBoss, "closed") rc = Dummy("rc", events, IRendezvousConnector, "stop") n = Dummy("n", events, INameplate, "close") m = Dummy("m", events, IMailbox, "close") d = Dummy("d", events, IDilator, "stop") t.wire(b, rc, n, m, d) return t, b, rc, n, m, events # there are three events, and we need to test all orderings of them def _do_test(self, ev1, ev2, ev3): t, b, rc, n, m, events = self.build() input_events = { "mailbox": lambda: t.mailbox_done(), "nameplate": lambda: t.nameplate_done(), "rc": lambda: t.close("happy"), } close_events = [ ("n.close", ), ("m.close", "happy"), ] if ev1 == "mailbox": close_events.remove(("m.close", "happy")) elif ev1 == "nameplate": close_events.remove(("n.close",)) input_events[ev1]() expected = [] if ev1 == "rc": expected.extend(close_events) self.assertEqual(events, expected) events[:] = [] if ev2 == "mailbox": close_events.remove(("m.close", "happy")) elif ev2 == "nameplate": close_events.remove(("n.close",)) input_events[ev2]() expected = [] if ev2 == "rc": expected.extend(close_events) self.assertEqual(events, expected) events[:] = [] if ev3 == "mailbox": close_events.remove(("m.close", "happy")) elif ev3 == "nameplate": close_events.remove(("n.close",)) input_events[ev3]() expected = [] if ev3 == "rc": expected.extend(close_events) expected.append(("rc.stop", )) self.assertEqual(events, expected) events[:] = [] t.stoppedRC() self.assertEqual(events, [("d.stop", )]) events[:] = [] t.stoppedD() self.assertEqual(events, [("b.closed", )]) def test_terminate(self): self._do_test("mailbox", "nameplate", "rc") self._do_test("mailbox", "rc", "nameplate") self._do_test("nameplate", "mailbox", "rc") self._do_test("nameplate", "rc", "mailbox") self._do_test("rc", "nameplate", "mailbox") self._do_test("rc", "mailbox", "nameplate") # TODO: test moods class MockBoss(_boss.Boss): def __attrs_post_init__(self): # self._build_workers() self._init_other_state() class Boss(unittest.TestCase): def build(self): events = [] wormhole = Dummy("w", events, None, "got_welcome", "got_code", "got_key", "got_verifier", "got_versions", "received", "closed") versions = {"app": "version1"} reactor = None eq = None cooperator = None journal = ImmediateJournal() tor_manager = None client_version = ("python", __version__) b = MockBoss(wormhole, "side", "url", "appid", versions, client_version, reactor, eq, cooperator, journal, tor_manager, timing.DebugTiming()) b._T = Dummy("t", events, ITerminator, "close") b._S = Dummy("s", events, ISend, "send") b._RC = Dummy("rc", events, IRendezvousConnector, "start") b._C = Dummy("c", events, ICode, "allocate_code", "input_code", "set_code") b._D = Dummy("d", events, IDilator, "got_wormhole_versions", "got_key") return b, events def test_basic(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.got_code("1-code") self.assertEqual(events, [("w.got_code", "1-code")]) events[:] = [] welcome = {"howdy": "how are ya"} b.rx_welcome(welcome) self.assertEqual(events, [ ("w.got_welcome", welcome), ]) events[:] = [] # pretend a peer message was correctly decrypted b.got_key(b"key") b.happy() b.got_verifier(b"verifier") b.got_message("version", b"{}") b.got_message("0", b"msg1") self.assertEqual(events, [ ("w.got_key", b"key"), ("d.got_key", b"key"), ("w.got_verifier", b"verifier"), ("d.got_wormhole_versions", {}), ("w.got_versions", {}), ("w.received", b"msg1"), ]) events[:] = [] b.send(b"msg2") self.assertEqual(events, [("s.send", "0", b"msg2")]) events[:] = [] b.close() self.assertEqual(events, [("t.close", "happy")]) events[:] = [] b.closed() self.assertEqual(events, [("w.closed", "happy")]) def test_unwelcome(self): b, events = self.build() unwelcome = {"error": "go away"} b.rx_welcome(unwelcome) self.assertEqual(events, [("t.close", "unwelcome")]) def test_lonely(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.got_code("1-code") self.assertEqual(events, [("w.got_code", "1-code")]) events[:] = [] b.close() self.assertEqual(events, [("t.close", "lonely")]) events[:] = [] b.closed() self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], errors.LonelyError) def test_server_error(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] orig = {} b.rx_error("server-error-msg", orig) self.assertEqual(events, [("t.close", "errory")]) events[:] = [] b.closed() self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], errors.ServerError) self.assertEqual(events[0][1].args[0], "server-error-msg") def test_internal_error(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.error(ValueError("catch me")) self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], ValueError) self.assertEqual(events[0][1].args[0], "catch me") def test_close_early(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.close() # before even w.got_code self.assertEqual(events, [("t.close", "lonely")]) events[:] = [] b.closed() self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], errors.LonelyError) def test_error_while_closing(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.close() self.assertEqual(events, [("t.close", "lonely")]) events[:] = [] b.error(ValueError("oops")) self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], ValueError) def test_scary_version(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.got_code("1-code") self.assertEqual(events, [("w.got_code", "1-code")]) events[:] = [] b.scared() self.assertEqual(events, [("t.close", "scary")]) events[:] = [] b.closed() self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], errors.WrongPasswordError) def test_scary_phase(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.got_code("1-code") self.assertEqual(events, [("w.got_code", "1-code")]) events[:] = [] b.happy() # phase=version b.scared() # phase=0 self.assertEqual(events, [("t.close", "scary")]) events[:] = [] b.closed() self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "w.closed") self.assertIsInstance(events[0][1], errors.WrongPasswordError) def test_unknown_phase(self): b, events = self.build() b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) events[:] = [] b.got_code("1-code") self.assertEqual(events, [("w.got_code", "1-code")]) events[:] = [] b.happy() # phase=version b.got_message("unknown-phase", b"spooky") self.assertEqual(events, []) self.flushLoggedErrors(errors._UnknownPhaseError) def test_set_code_bad_format(self): b, events = self.build() with self.assertRaises(errors.KeyFormatError): b.set_code("1 code") # wormhole should still be usable b.set_code("1-code") self.assertEqual(events, [("c.set_code", "1-code")]) def test_set_code_twice(self): b, events = self.build() b.set_code("1-code") with self.assertRaises(errors.OnlyOneCodeError): b.set_code("1-code") def test_input_code(self): b, events = self.build() b._C.retval = "helper" helper = b.input_code() self.assertEqual(events, [("c.input_code", )]) self.assertEqual(helper, "helper") with self.assertRaises(errors.OnlyOneCodeError): b.input_code() def test_allocate_code(self): b, events = self.build() wl = object() with mock.patch("wormhole._boss.PGPWordList", return_value=wl): b.allocate_code(3) self.assertEqual(events, [("c.allocate_code", 3, wl)]) with self.assertRaises(errors.OnlyOneCodeError): b.allocate_code(3) class Rendezvous(unittest.TestCase): def build(self): events = [] reactor = object() journal = ImmediateJournal() tor_manager = None client_version = ("python", __version__) rc = _rendezvous.RendezvousConnector( "ws://host:4000/v1", "appid", "side", reactor, journal, tor_manager, timing.DebugTiming(), client_version) b = Dummy("b", events, IBoss, "error") n = Dummy("n", events, INameplate, "connected", "lost") m = Dummy("m", events, IMailbox, "connected", "lost") a = Dummy("a", events, IAllocator, "connected", "lost") l = Dummy("l", events, ILister, "connected", "lost") t = Dummy("t", events, ITerminator) rc.wire(b, n, m, a, l, t) return rc, events def test_basic(self): rc, events = self.build() del rc, events def test_websocket_failure(self): # if the TCP connection succeeds, but the subsequent WebSocket # negotiation fails, then we'll see an onClose without first seeing # onOpen rc, events = self.build() rc.ws_close(False, 1006, "connection was closed uncleanly") # this should cause the ClientService to be shut down, and an error # delivered to the Boss self.assertEqual(len(events), 1, events) self.assertEqual(events[0][0], "b.error") self.assertIsInstance(events[0][1], errors.ServerConnectionError) self.assertEqual(str(events[0][1]), "connection was closed uncleanly") def test_websocket_lost(self): # if the TCP connection succeeds, and negotiation completes, then the # connection is lost, several machines should be notified rc, events = self.build() ws = mock.Mock() def notrandom(length): return b"\x00" * length with mock.patch("os.urandom", notrandom): rc.ws_open(ws) self.assertEqual(events, [ ("n.connected", ), ("m.connected", ), ("l.connected", ), ("a.connected", ), ]) events[:] = [] def sent_messages(ws): for c in ws.mock_calls: self.assertEqual(c[0], "sendMessage", ws.mock_calls) self.assertEqual(c[1][1], False, ws.mock_calls) yield bytes_to_dict(c[1][0]) self.assertEqual( list(sent_messages(ws)), [ dict( appid="appid", side="side", client_version=["python", __version__], id="0000", type="bind"), ]) rc.ws_close(True, None, None) self.assertEqual(events, [ ("n.lost", ), ("m.lost", ), ("l.lost", ), ("a.lost", ), ]) def test_endpoints(self): # parse different URLs and check the tls status of each reactor = object() journal = ImmediateJournal() tor_manager = None client_version = ("python", __version__) rc = _rendezvous.RendezvousConnector( "ws://host:4000/v1", "appid", "side", reactor, journal, tor_manager, timing.DebugTiming(), client_version) new_ep = object() with mock.patch("twisted.internet.endpoints.HostnameEndpoint", return_value=new_ep) as he: ep = rc._make_endpoint("ws://host:4000/v1") self.assertEqual(he.mock_calls, [mock.call(reactor, "host", 4000)]) self.assertIs(ep, new_ep) new_ep = object() with mock.patch("twisted.internet.endpoints.HostnameEndpoint", return_value=new_ep) as he: ep = rc._make_endpoint("ws://host/v1") self.assertEqual(he.mock_calls, [mock.call(reactor, "host", 80)]) self.assertIs(ep, new_ep) new_ep = object() with mock.patch("twisted.internet.endpoints.clientFromString", return_value=new_ep) as cfs: ep = rc._make_endpoint("wss://host:4000/v1") self.assertEqual(cfs.mock_calls, [mock.call(reactor, "tls:host:4000")]) self.assertIs(ep, new_ep) new_ep = object() with mock.patch("twisted.internet.endpoints.clientFromString", return_value=new_ep) as cfs: ep = rc._make_endpoint("wss://host/v1") self.assertEqual(cfs.mock_calls, [mock.call(reactor, "tls:host:443")]) self.assertIs(ep, new_ep) tor_manager = mock.Mock() directlyProvides(tor_manager, ITorManager) rc = _rendezvous.RendezvousConnector( "ws://host:4000/v1", "appid", "side", reactor, journal, tor_manager, timing.DebugTiming(), client_version) tor_manager.mock_calls[:] = [] ep = rc._make_endpoint("ws://host:4000/v1") self.assertEqual(tor_manager.mock_calls, [mock.call.stream_via("host", 4000, tls=False)]) tor_manager.mock_calls[:] = [] ep = rc._make_endpoint("ws://host/v1") self.assertEqual(tor_manager.mock_calls, [mock.call.stream_via("host", 80, tls=False)]) tor_manager.mock_calls[:] = [] ep = rc._make_endpoint("wss://host:4000/v1") self.assertEqual(tor_manager.mock_calls, [mock.call.stream_via("host", 4000, tls=True)]) tor_manager.mock_calls[:] = [] ep = rc._make_endpoint("wss://host/v1") self.assertEqual(tor_manager.mock_calls, [mock.call.stream_via("host", 443, tls=True)]) # TODO # #Send # #Mailbox # #Nameplate # #Terminator # Boss # RendezvousConnector (not a state machine) # #Input: exercise helper methods # #wordlist # test idempotency / at-most-once where applicable
mit
8d334cba3d167d66333e972c9762d176
32.989418
79
0.533226
3.508252
false
true
false
false
posativ/isso
isso/core.py
1
2660
# -*- encoding: utf-8 -*- import time import logging import threading import multiprocessing try: import uwsgi except ImportError: uwsgi = None import _thread as thread from isso.utils.cache import NullCache from isso.utils.cache import SimpleCache logger = logging.getLogger("isso") class Cache: """Wrapper around werkzeug's cache class, to make it compatible to uWSGI's cache framework. """ def __init__(self, cache): self.cache = cache def get(self, cache, key): return self.cache.get(key) def set(self, cache, key, value): return self.cache.set(key, value) def delete(self, cache, key): return self.cache.delete(key) class Mixin(object): def __init__(self, conf): self.lock = threading.Lock() self.cache = Cache(NullCache()) def notify(self, subject, body, retries=5): pass def threaded(func): """ Decorator to execute each :param func: call in a separate thread. """ def dec(self, *args, **kwargs): thread.start_new_thread(func, (self, ) + args, kwargs) return dec class ThreadedMixin(Mixin): def __init__(self, conf): super(ThreadedMixin, self).__init__(conf) if conf.getboolean("moderation", "enabled"): self.purge(conf.getint("moderation", "purge-after")) self.cache = Cache(SimpleCache(threshold=1024, default_timeout=3600)) @threaded def purge(self, delta): while True: with self.lock: self.db.comments.purge(delta) time.sleep(delta) class ProcessMixin(ThreadedMixin): def __init__(self, conf): super(ProcessMixin, self).__init__(conf) self.lock = multiprocessing.Lock() class uWSGICache(object): """Uses uWSGI Caching Framework. INI configuration: .. code-block:: ini cache2 = name=hash,items=1024,blocksize=32 """ @classmethod def get(self, cache, key): return uwsgi.cache_get(key, cache) @classmethod def set(self, cache, key, value): uwsgi.cache_set(key, value, 3600, cache) @classmethod def delete(self, cache, key): uwsgi.cache_del(key, cache) class uWSGIMixin(Mixin): def __init__(self, conf): super(uWSGIMixin, self).__init__(conf) self.lock = multiprocessing.Lock() self.cache = uWSGICache timedelta = conf.getint("moderation", "purge-after") def purge(signum): return self.db.comments.purge(timedelta) uwsgi.register_signal(1, "", purge) uwsgi.add_timer(1, timedelta) # run purge once purge(1)
mit
d4eb0e8e4c764192071a18407e08cfc3
20.111111
77
0.615789
3.751763
false
false
false
false
enkore/i3pystatus
docs/module_docs.py
9
6310
import pkgutil import importlib import sphinx.application from docutils.parsers.rst import Directive from docutils.nodes import paragraph from docutils.statemachine import StringList import i3pystatus.core.settings import i3pystatus.core.modules from i3pystatus.core.imputil import ClassFinder from i3pystatus.core.color import ColorRangeModule IGNORE_MODULES = ("__main__", "core", "tools") def is_module(obj): return (isinstance(obj, type) and issubclass(obj, i3pystatus.core.settings.SettingsBase) and not obj.__module__.startswith("i3pystatus.core.")) def fail_on_missing_dependency_hints(obj, lines): # We can automatically check in some cases if we forgot something if issubclass(obj, ColorRangeModule): if all("colour" not in line for line in lines): raise ValueError(">>> Module <{}> uses ColorRangeModule and should document it <<<\n" "> Requires the PyPI package ``colour``".format(obj.__name__)) def check_settings_consistency(obj, settings): errs = [] for setting in settings: if not setting.required and setting.default is setting.sentinel: errs.append("<" + setting.name + ">") if errs: raise ValueError(">>> Module <{}> has non-required setting(s) {} with no default! <<<\n" .format(obj.__name__, ", ".join(errs))) def process_docstring(app, what, name, obj, options, lines): class Setting: doc = "" required = False default = sentinel = object() empty = object() def __init__(self, cls, setting): if isinstance(setting, tuple): self.name = setting[0] self.doc = setting[1] else: self.name = setting if self.name in cls.required: self.required = True elif hasattr(cls, self.name): default = getattr(cls, self.name) if isinstance(default, str) and not len(default)\ or default is None: default = self.empty self.default = default def __str__(self): attrs = [] if self.required: attrs.append("required") if self.default not in [self.sentinel, self.empty]: attrs.append("default: ``{default}``".format(default=self.default)) if self.default is self.empty: attrs.append("default: *empty*") formatted = "* **{name}** {attrsf} {doc}".format( name=self.name, doc="– " + self.doc if self.doc else "", attrsf=" ({attrs})".format(attrs=", ".join(attrs)) if attrs else "") return formatted if is_module(obj) and obj.settings: fail_on_missing_dependency_hints(obj, lines) if issubclass(obj, i3pystatus.core.modules.Module): mod = obj.__module__ if mod.startswith("i3pystatus."): mod = mod[len("i3pystatus."):] lines[0:0] = [ ".. raw:: html", "", " <div class='modheader'>" + "Module name: <code class='modname descclassname'>" + mod + "</code> " + "(class <code class='descclassname'>" + name + "</code>)" + "</div>", "", ] else: lines[0:0] = [ ".. raw:: html", "", " <div class='modheader'>class <code class='descclassname'>" + name + "</code></div>", "", ] lines.append(".. rubric:: Settings") lines.append("") settings = [Setting(obj, setting) for setting in obj.settings] lines += map(str, settings) check_settings_consistency(obj, settings) lines.append("") def process_signature(app, what, name, obj, options, signature, return_annotation): if is_module(obj): return ("", return_annotation) def get_modules(path, package): modules = [] for finder, modname, is_package in pkgutil.iter_modules(path): if modname not in IGNORE_MODULES: modules.append(get_module(finder, modname, package)) return modules def get_module(finder, modname, package): fullname = "{package}.{modname}".format(package=package, modname=modname) return (modname, finder.find_loader(fullname)[0].load_module(fullname)) def get_all(module_path, modname, basecls): mods = [] finder = ClassFinder(basecls) for name, module in get_modules(module_path, modname): classes = finder.get_matching_classes(module) found = [] for cls in classes: if cls.__name__ not in found: found.append(cls.__name__) mods.append((module.__name__, cls.__name__)) return sorted(mods, key=lambda module: module[0]) def generate_automodules(path, name, basecls): modules = get_all(path, name, basecls) contents = [] for mod in modules: contents.append("* :py:mod:`~{}`".format(mod[0])) contents.append("") for mod in modules: contents.append(".. _{}:\n".format(mod[0].split(".")[-1])) contents.append(".. automodule:: {}".format(mod[0])) contents.append(" :members: {}\n".format(mod[1])) return contents class AutogenDirective(Directive): required_arguments = 2 has_content = True def run(self): # Raise an error if the directive does not have contents. self.assert_has_content() modname = self.arguments[0] modpath = importlib.import_module(modname).__path__ basecls = getattr(i3pystatus.core.modules, self.arguments[1]) contents = [] for e in self.content: contents.append(e) contents.append("") contents.extend(generate_automodules(modpath, modname, basecls)) node = paragraph() self.state.nested_parse(StringList(contents), 0, node) return [node] def setup(app: sphinx.application.Sphinx): app.add_directive("autogen", AutogenDirective) app.connect("autodoc-process-docstring", process_docstring) app.connect("autodoc-process-signature", process_signature)
mit
83ef9ca2d7e84c5953493f040a1c1891
31.515464
105
0.57435
4.128272
false
false
false
false
enkore/i3pystatus
i3pystatus/moon.py
6
3188
from i3pystatus import IntervalModule, formatp import datetime import math import decimal import os from i3pystatus.core.util import TimeWrapper dec = decimal.Decimal class MoonPhase(IntervalModule): """ Available Formatters status: Allows for mapping of current moon phase - New Moon: - Waxing Crescent: - First Quarter: - Waxing Gibbous: - Full Moon: - Waning Gibbous: - Last Quarter: - Waning Crescent: """ settings = ( "format", ("status", "Current moon phase"), ("illum", "Percentage that is illuminated"), ("color", "Set color"), ("moonicon", 'Set icon') ) format = "{illum} {status} {moonicon}" interval = 60 * 60 * 2 # every 2 hours status = { "New Moon": "NM", "Waxing Crescent": "WaxCres", "First Quarter": "FQ", "Waxing Gibbous": "WaxGib", "Full Moon": "FM", "Waning Gibbous": "WanGib", "Last Quarter": "LQ", "Waning Crescent": "WanCres", } color = { "New Moon": "#00BDE5", "Waxing Crescent": "#138DD8", "First Quarter": "#265ECC", "Waxing Gibbous": "#392FBF", "Full Moon": "#4C00B3", "Waning Gibbous": "#871181", "Last Quarter": "#C32250", "Waning Crescent": "#FF341F", } moonicon = { "New Moon": b'\xf0\x9f\x8c\x91'.decode(), "Waxing Crescent": b'\xf0\x9f\x8c\x92'.decode(), "First Quarter": b'\xf0\x9f\x8c\x93'.decode(), "Waxing Gibbous": b'\xf0\x9f\x8c\x94'.decode(), "Full Moon": b'\xf0\x9f\x8c\x95'.decode(), "Waning Gibbous": b'\xf0\x9f\x8c\x96'.decode(), "Last Quarter": b'\xf0\x9f\x8c\x97'.decode(), "Waning Crescent": b'\xf0\x9f\x8c\x98'.decode() } def pos(now=None): days_in_second = 86400 now = datetime.datetime.now() difference = now - datetime.datetime(2001, 1, 1) days = dec(difference.days) + (dec(difference.seconds) / dec(days_in_second)) lunarCycle = dec("0.20439731") + (days * dec("0.03386319269")) return lunarCycle % dec(1) def current_phase(self): lunarCycle = self.pos() index = (lunarCycle * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent", }[int(index) & 7] def illum(self): phase = 0 lunarCycle = float(self.pos()) * 100 if lunarCycle > 50: phase = 100 - lunarCycle else: phase = lunarCycle * 2 return phase def run(self): fdict = { "status": self.status[self.current_phase()], "illum": self.illum(), "moonicon": self.moonicon[self.current_phase()] } self.data = fdict self.output = { "full_text": formatp(self.format, **fdict), "color": self.color[self.current_phase()], }
mit
95e9f7328e36bd2081737477306bcc7e
24.504
85
0.526662
3.065385
false
false
false
false
warner/magic-wormhole
src/wormhole/ipaddrs.py
1
2927
# no unicode_literals # Find all of our ip addresses. From tahoe's src/allmydata/util/iputil.py import errno import os import re import subprocess from sys import platform from twisted.python.procutils import which # Wow, I'm really amazed at home much mileage we've gotten out of calling # the external route.exe program on windows... It appears to work on all # versions so far. Still, the real system calls would much be preferred... # ... thus wrote Greg Smith in time immemorial... _win32_re = re.compile( (r'^\s*\d+\.\d+\.\d+\.\d+\s.+\s' r'(?P<address>\d+\.\d+\.\d+\.\d+)\s+(?P<metric>\d+)\s*$'), flags=re.M | re.I | re.S) _win32_commands = (('route.exe', ('print', ), _win32_re), ) # These work in most Unices. _addr_re = re.compile( r'^\s*inet [a-zA-Z]*:?(?P<address>\d+\.\d+\.\d+\.\d+)[\s/].+$', flags=re.M | re.I | re.S) _unix_commands = ( ('/bin/ip', ('addr', ), _addr_re), ('/sbin/ip', ('addr', ), _addr_re), ('/sbin/ifconfig', ('-a', ), _addr_re), ('/usr/sbin/ifconfig', ('-a', ), _addr_re), ('/usr/etc/ifconfig', ('-a', ), _addr_re), ('ifconfig', ('-a', ), _addr_re), ('/sbin/ifconfig', (), _addr_re), ) def find_addresses(): # originally by Greg Smith, hacked by Zooko and then Daira # We don't reach here for cygwin. if platform == 'win32': commands = _win32_commands else: commands = _unix_commands for (pathtotool, args, regex) in commands: # If pathtotool is a fully qualified path then we just try that. # If it is merely an executable name then we use Twisted's # "which()" utility and try each executable in turn until one # gives us something that resembles a dotted-quad IPv4 address. if os.path.isabs(pathtotool): exes_to_try = [pathtotool] else: exes_to_try = which(pathtotool) for exe in exes_to_try: try: addresses = _query(exe, args, regex) except Exception: addresses = [] if addresses: return addresses return ["127.0.0.1"] def _query(path, args, regex): env = {'LANG': 'en_US.UTF-8'} trial = 0 while True: trial += 1 try: p = subprocess.Popen( [path] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, universal_newlines=True) (output, err) = p.communicate() break except OSError as e: if e.errno == errno.EINTR and trial < 5: continue raise addresses = [] outputsplit = output.split('\n') for outline in outputsplit: m = regex.match(outline) if m: addr = m.group('address') if addr not in addresses: addresses.append(addr) return addresses
mit
d1af2aaa107bf5de7d36db5ccee2f8e0
29.489583
75
0.551076
3.48038
false
true
false
false
enkore/i3pystatus
i3pystatus/weather/weathercom.py
2
12461
import json import re from datetime import datetime from html.parser import HTMLParser from urllib.request import Request, urlopen from i3pystatus.core.util import internet, require from i3pystatus.weather import WeatherBackend class WeathercomHTMLParser(HTMLParser): ''' Obtain data points required by the Weather.com API which are obtained through some other source at runtime and added as <script> elements to the page source. ''' user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0' def __init__(self, logger): self.logger = logger super(WeathercomHTMLParser, self).__init__() def get_weather_data(self, url): self.logger.debug(f'Making request to {url} to retrieve weather data') self.weather_data = None req = Request(url, headers={'User-Agent': self.user_agent}) with urlopen(req) as content: try: content_type = dict(content.getheaders())['Content-Type'] charset = re.search(r'charset=(.*)', content_type).group(1) except AttributeError: charset = 'utf-8' html = content.read().decode(charset) try: self.feed(html) except Exception: self.logger.exception( 'Exception raised while parsing forecast page', exc_info=True ) def load_json(self, json_input): self.logger.debug(f'Loading the following data as JSON: {json_input}') try: return json.loads(json_input) except json.decoder.JSONDecodeError as exc: self.logger.debug(f'Error loading JSON: {exc}') self.logger.debug(f'String that failed to load: {json_input}') return None def handle_data(self, content): ''' Sometimes the weather data is set under an attribute of the "window" DOM object. Sometimes it appears as part of a javascript function. Catch either possibility. ''' if self.weather_data is not None: # We've already found weather data, no need to continue parsing return content = content.strip().rstrip(';') try: tag_text = self.get_starttag_text().lower() except AttributeError: tag_text = '' if tag_text.startswith('<script'): # Look for feed information embedded as a javascript variable begin = content.find('window.__data') if begin != -1: weather_data = None self.logger.debug('Located window.__data') # Strip the "window.__data=" from the beginning and load json raw_json = content[begin:].split('=', 1)[1].lstrip() if re.match(r'^JSON\.parse\("', raw_json): raw_json = re.sub(r'^JSON\.parse\("', '', raw_json) raw_json = re.sub(r'"\);?$', '', raw_json) raw_json = raw_json.replace(r'\"', '"').replace(r'\\', '\\') json_data = self.load_json(raw_json) if json_data is not None: try: weather_data = json_data['dal'] except KeyError: pass if weather_data is None: self.logger.debug( 'Failed to locate weather data in the ' f'following data: {json_data}' ) else: self.weather_data = weather_data return class Weathercom(WeatherBackend): ''' This module gets the weather from weather.com. The ``location_code`` parameter should be set to the location code from weather.com. To obtain this code, search for your location on weather.com, and when you go to the forecast page, the code you need will be everything after the last slash in the URL (e.g. ``94107:4:US``, or ``8b7867695971473a260df2c5d49ff92dc9079dcb673c545f5f107f5c4ab30732``). .. _weather-usage-weathercom: .. rubric:: Usage example .. code-block:: python from i3pystatus import Status from i3pystatus.weather import weathercom status = Status(logfile='/home/username/var/i3pystatus.log') status.register( 'weather', format='{condition} {current_temp}{temp_unit}[ {icon}][ Hi: {high_temp}][ Lo: {low_temp}][ {update_error}]', interval=900, colorize=True, hints={'markup': 'pango'}, backend=weathercom.Weathercom( location_code='94107:4:US', units='imperial', update_error='<span color="#ff0000">!</span>', ), ) status.run() See :ref:`here <weather-formatters>` for a list of formatters which can be used. ''' settings = ( ('location_code', 'Location code from www.weather.com'), ('units', '\'metric\' or \'imperial\''), ('update_error', 'Value for the ``{update_error}`` formatter when an ' 'error is encountered while checking weather data'), ) required = ('location_code',) location_code = None units = 'metric' update_error = '!' url_template = 'https://weather.com/{locale}/weather/today/l/{location_code}' # This will be set in the init based on the passed location code conditions_url = None def init(self): if self.location_code is not None: # Ensure that the location code is a string, in the event that a # ZIP code (or other all-numeric code) is passed as a non-string. self.location_code = str(self.location_code) # Setting the locale to en-AU returns units in metric. Leaving it blank # causes weather.com to return the default, which is imperial. self.locale = 'en-CA' if self.units == 'metric' else '' self.conditions_url = self.url_template.format(**vars(self)) self.parser = WeathercomHTMLParser(self.logger) @require(internet) def check_weather(self): ''' Fetches the current weather from wxdata.weather.com service. ''' if self.units not in ('imperial', 'metric'): raise Exception("units must be one of (imperial, metric)!") if self.location_code is None: self.logger.error( 'A location_code is required to check Weather.com. See the ' 'documentation for more information.' ) self.data['update_error'] = self.update_error return self.data['update_error'] = '' try: self.parser.get_weather_data(self.conditions_url) if self.parser.weather_data is None: self.logger.error( 'Failed to read weather data from page. Run module with ' 'debug logging to get more information.' ) self.data['update_error'] = self.update_error return self.logger.debug(f'Parsed weather data: {self.parser.weather_data}') try: observed = self.parser.weather_data['getSunV3CurrentObservationsUrlConfig'] # Observation data stored under a sub-key containing the # lat/long coordinates, locale info, etc. For example: # # geocode:41.77,-88.35:language:en-US:units:e # # Since this is the only key under "Observation", we can just # use next(iter(observed)) to get it. observed = observed[next(iter(observed))]['data'] except KeyError: self.logger.error( 'Failed to retrieve current conditions from API response. ' 'Run module with debug logging to get more information.' ) self.data['update_error'] = self.update_error return try: forecast = self.parser.weather_data['getSunV3DailyForecastWithHeadersUrlConfig'] # Same as above, use next(iter(forecast)) to drill down to the # correct nested dict level. forecast = forecast[next(iter(forecast))]['data'] except (IndexError, KeyError): self.logger.error( 'Failed to retrieve forecast data from API response. ' 'Run module with debug logging to get more information.' ) self.data['update_error'] = self.update_error return try: location = self.parser.weather_data['getSunV3LocationPointUrlConfig'] # Again, same technique as above used to get down to the # correct nested dict level. location = location[next(iter(location))] self.city_name = location['data']['location']['displayName'] except KeyError: self.logger.warning( 'Failed to get city name from API response, falling back ' f'to location code {self.location_code}' ) self.city_name = self.location_code try: observation_time_str = str(observed.get('validTimeLocal', '')) observation_time = datetime.strptime(observation_time_str, '%Y-%d-%yT%H:%M:%S%z') except (ValueError, AttributeError): observation_time = datetime.fromtimestamp(0) try: pressure_trend_str = observed.get('pressureTendencyTrend', '').lower() except AttributeError: pressure_trend_str = '' if pressure_trend_str == 'rising': pressure_trend = '+' elif pressure_trend_str == 'falling': pressure_trend = '-' else: pressure_trend = '' try: high_temp = forecast.get('temperatureMax', [])[0] or '' except (AttributeError, IndexError): high_temp = '' try: low_temp = forecast.get('temperatureMin', [])[0] or '' except (AttributeError, IndexError): low_temp = '' if self.units == 'imperial': temp_unit = '°F' wind_unit = 'mph' pressure_unit = 'in' visibility_unit = 'mi' else: temp_unit = '°C' wind_unit = 'kph' pressure_unit = 'mb' visibility_unit = 'km' self.data['city'] = self.city_name self.data['condition'] = str(observed.get('wxPhraseMedium', '')) self.data['observation_time'] = observation_time self.data['current_temp'] = str(observed.get('temperature', '')) self.data['low_temp'] = str(low_temp) self.data['high_temp'] = str(high_temp) self.data['temp_unit'] = temp_unit self.data['feelslike'] = str(observed.get('temperatureFeelsLike', '')) self.data['dewpoint'] = str(observed.get('temperatureDewPoint', '')) self.data['wind_speed'] = str(observed.get('windSpeed', '')) self.data['wind_unit'] = wind_unit self.data['wind_direction'] = str(observed.get('windDirectionCardinal', '')) # Gust can be None, using "or" to ensure empty string in this case self.data['wind_gust'] = str(observed.get('windGust', '') or '') self.data['pressure'] = str(observed.get('pressureAltimeter', '')) self.data['pressure_unit'] = pressure_unit self.data['pressure_trend'] = pressure_trend self.data['visibility'] = str(observed.get('visibility', '')) self.data['visibility_unit'] = visibility_unit self.data['humidity'] = str(observed.get('relativeHumidity', '')) self.data['uv_index'] = str(observed.get('uvIndex', '')) except Exception: # Don't let an uncaught exception kill the update thread self.logger.exception('Uncaught error occurred while checking weather') self.data['update_error'] = self.update_error
mit
b5295036e95ecd5a730b7f77f9373a77
40.668896
120
0.550445
4.356294
false
false
false
false
enkore/i3pystatus
i3pystatus/pagerduty.py
4
2349
from i3pystatus import IntervalModule from i3pystatus.core.util import internet, require, formatp import pypd __author__ = 'chestm007' class PagerDuty(IntervalModule): """ Module to get the current incidents in PD Requires `pypd` Formatters: * `{num_incidents}` - current number of incidents unresolved * `{num_acknowledged_incidents}` - as it sounds * `{num_triggered_incidents}` - number of unacknowledged incidents Example: .. code-block:: python status.register( 'pagerduty', api_key='mah_api_key', user_id='LKJ19QW' ) """ settings = ( 'format', ('api_key', 'pagerduty api key'), ('color', 'module text color'), ('interval', 'refresh interval'), ('user_id', 'your pagerduty user id, shows up in the url when viewing your profile ' '`https://subdomain.pagerduty.com/users/<user_id>`') ) required = ['api_key'] format = '{num_triggered_incidents} triggered {num_acknowledged_incidents} acknowledged' api_key = None color = '#AA0000' interval = 60 user_id = None api_search_dict = dict(statuses=['triggered', 'acknowledged']) num_acknowledged_incidents = None num_triggered_incidents = None num_incidents = None def init(self): pypd.api_key = self.api_key if self.user_id: self.api_search_dict['user_ids'] = [self.user_id] @require(internet) def run(self): pd_incidents = pypd.Incident.find(**self.api_search_dict) incidents = { 'acknowledged': [], 'triggered': [], 'all': [] } for incident in pd_incidents: incidents['all'].append(incident) status = incident.get('status') if status == 'acknowledged': incidents['acknowledged'].append(incident) elif status == 'triggered': incidents['triggered'].append(incident) self.num_acknowledged_incidents = len(incidents.get('acknowledged')) self.num_triggered_incidents = len(incidents.get('triggered')) self.num_incidents = len(incidents.get('all')) self.output = dict( full_text=formatp(self.format, **vars(self)), color=self.color )
mit
86162851323179b93f71dbc0496bc4c4
28
93
0.58493
3.670313
false
false
false
false
enkore/i3pystatus
i3pystatus/yubikey.py
3
3446
import re import os import time from i3pystatus import IntervalModule from i3pystatus.core.command import run_through_shell class Yubikey(IntervalModule): """ This module allows you to lock and unlock your Yubikey in order to avoid the OTP to be triggered accidentally. @author Daniel Theodoro <daniel.theodoro AT gmail.com> """ interval = 1 format = "Yubikey: 🔒" unlocked_format = "Yubikey: 🔓" timeout = 5 color = "#00FF00" unlock_color = "#FF0000" settings = ( ("format", "Format string"), ("unlocked_format", "Format string when the key is unlocked"), ("timeout", "How long the Yubikey will be unlocked (default: 5)"), ("color", "Standard color"), ("unlock_color", "Set the color used when the Yubikey is unlocked"), ) on_leftclick = ["set_lock", True] find_regex = re.compile( r".*yubikey.*id=(?P<yubid>\d+).*$", re.IGNORECASE ) status_regex = re.compile( r".*device enabled.*(?P<status>\d)$", re.IGNORECASE ) lock_file = f"/var/tmp/Yubikey-{os.geteuid()}.lock" def __init__(self): super().__init__() @property def _device_id(self): command = run_through_shell("xinput list") rval = "" if command.rc == 0: for line in command.out.splitlines(): match = self.find_regex.match(line) if match: rval = match.groupdict().get("yubid", "") break return rval def device_status(self): rval = "notfound" if not self._device_id: return rval result = run_through_shell(f"xinput list-props {self._device_id}") if result.rc == 0: match = self.status_regex.match(result.out.splitlines()[1]) if match and "status" in match.groupdict(): status = int(match.groupdict()["status"]) if status: rval = "unlocked" else: rval = "locked" return rval def _check_lock(self): try: st = os.stat(self.lock_file) if int(time.time() - st.st_ctime) > self.timeout: self.set_lock() except IOError: self.set_lock() def set_lock(self, unlock=False): if unlock: command = "enable" else: command = "disable" run_through_shell(f"xinput {command} {self._device_id}") open(self.lock_file, mode="w").close() def _clear_lock(self): try: os.unlink(self.lock_file) except FileNotFoundError: pass def run(self): status = self.device_status() if status == "notfound": self._clear_lock() self.output = { "full_text": "", } else: if status == "unlocked": self.output = { "full_text": self.unlocked_format, "color": self.unlock_color } self._check_lock() elif status == "locked": self.output = { "full_text": self.format, "color": self.color } else: self.output = { "full_text": f"Error: {status}", }
mit
a8f154f935bfbf95d2c707f96f7c8533
24.864662
76
0.498837
3.976879
false
false
false
false
fxsjy/jieba
jieba/posseg/viterbi.py
71
1610
import sys import operator MIN_FLOAT = -3.14e100 MIN_INF = float("-inf") if sys.version_info[0] > 2: xrange = range def get_top_states(t_state_v, K=4): return sorted(t_state_v, key=t_state_v.__getitem__, reverse=True)[:K] def viterbi(obs, states, start_p, trans_p, emit_p): V = [{}] # tabular mem_path = [{}] all_states = trans_p.keys() for y in states.get(obs[0], all_states): # init V[0][y] = start_p[y] + emit_p[y].get(obs[0], MIN_FLOAT) mem_path[0][y] = '' for t in xrange(1, len(obs)): V.append({}) mem_path.append({}) #prev_states = get_top_states(V[t-1]) prev_states = [ x for x in mem_path[t - 1].keys() if len(trans_p[x]) > 0] prev_states_expect_next = set( (y for x in prev_states for y in trans_p[x].keys())) obs_states = set( states.get(obs[t], all_states)) & prev_states_expect_next if not obs_states: obs_states = prev_states_expect_next if prev_states_expect_next else all_states for y in obs_states: prob, state = max((V[t - 1][y0] + trans_p[y0].get(y, MIN_INF) + emit_p[y].get(obs[t], MIN_FLOAT), y0) for y0 in prev_states) V[t][y] = prob mem_path[t][y] = state last = [(V[-1][y], y) for y in mem_path[-1].keys()] # if len(last)==0: # print obs prob, state = max(last) route = [None] * len(obs) i = len(obs) - 1 while i >= 0: route[i] = state state = mem_path[i][state] i -= 1 return (prob, route)
mit
f01d1dfc4dc5e8e75dbf6b70382edf0c
29.377358
91
0.520497
2.900901
false
false
false
false
alejandroautalan/pygubu
src/pygubu/plugins/tk/tkstdwidgets.py
1
42688
# encoding: utf-8 import logging import tkinter as tk from pygubu.i18n import _ from pygubu.api.v1 import BuilderObject, register_widget from pygubu.component.builderobject import ( CB_TYPES, EntryBaseBO, PanedWindowBO, PanedWindowPaneBO, ) logger = logging.getLogger(__name__) # # tkinter widgets # _toplevel_87 = tuple() if tk.TkVersion >= 8.7: _toplevel_87 = ("backgroundimage", "tile") class TKToplevel(BuilderObject): class_ = tk.Toplevel container = True layout_required = False container_layout = True allowed_parents = ("root",) # maxchildren = 2 # A menu and a frame OPTIONS_STANDARD = ( "borderwidth", "cursor", "highlightbackground", "highlightcolor", "highlightthickness", "padx", "pady", "relief", "takefocus", ) OPTIONS_SPECIFIC = ( "background", "class_", "container", "height", "width", ) + _toplevel_87 OPTIONS_CUSTOM = ( "title", "geometry", "overrideredirect", "minsize", "maxsize", "resizable", "iconbitmap", "iconphoto", ) ro_properties = ("container",) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC + OPTIONS_CUSTOM RESIZABLE = { "both": (True, True), "horizontally": (True, False), "vertically": (False, True), "none": (False, False), } def realize(self, parent): args = self._get_init_args() master = parent.get_child_master() if master is None and tk._default_root is None: self.widget = tk.Tk() else: self.widget = self.class_(master, **args) return self.widget # def layout(self, target=None): # we marked this widget as not allowed to edit layoutu # pass def _set_property(self, target_widget, pname, value): method_props = ("geometry", "overrideredirect", "title") if pname in method_props: method = getattr(target_widget, pname) method(value) elif pname == "resizable" and value: target_widget.resizable(*self.RESIZABLE[value]) elif pname == "maxsize": if "|" in value: w, h = value.split("|") target_widget.maxsize(w, h) elif pname == "minsize": if "|" in value: w, h = value.split("|") target_widget.minsize(w, h) elif pname == "iconphoto": icon = self.builder.get_image(value) target_widget.iconphoto(True, icon) elif pname == "iconbitmap": icon = self.builder.get_iconbitmap(value) target_widget.iconbitmap(icon) else: super(TKToplevel, self)._set_property(target_widget, pname, value) # # Code generation methods # def _code_set_property(self, targetid, pname, value, code_bag): if pname in ("geometry", "overrideredirect", "title"): line = f'{targetid}.{pname}("{value}")' code_bag[pname] = (line,) elif pname == "resizable": p1, p2 = self.RESIZABLE[value] line = "{0}.resizable({1}, {2})".format(targetid, p1, p2) code_bag[pname] = (line,) elif pname in ("maxsize", "minsize"): if "|" in value: w, h = value.split("|") line = "{0}.{1}({2}, {3})".format(targetid, pname, w, h) code_bag[pname] = (line,) elif pname == "iconbitmap": bitmap = self.builder.code_create_iconbitmap(value) line = f'{targetid}.iconbitmap("{bitmap}")' code_bag[pname] = (line,) elif pname == "iconphoto": image = self.builder.code_create_image(value) line = "{0}.iconphoto(True, {1})".format(targetid, image) code_bag[pname] = (line,) else: super(TKToplevel, self)._code_set_property( targetid, pname, value, code_bag ) register_widget( "tk.Toplevel", TKToplevel, "Toplevel", (_("Containers"), "tk", "ttk") ) class TKFrame(BuilderObject): OPTIONS_STANDARD = ( "borderwidth", "cursor", "highlightbackground", "highlightcolor", "highlightthickness", "padx", "pady", "relief", "takefocus", ) OPTIONS_SPECIFIC = ( "background", "class_", "container", "height", "width", ) class_ = tk.Frame container = True container_layout = True properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC ro_properties = ("class_", "container") register_widget("tk.Frame", TKFrame, "Frame", (_("Containers"), "tk")) class TKLabel(BuilderObject): OPTIONS_STANDARD = ( "activebackground", "activeforeground", "anchor", "background", "bitmap", "borderwidth", "compound", "cursor", "disabledforeground", "font", "foreground", "height", "highlightbackground", "highlightcolor", "highlightthickness", "image", "justify", "padx", "pady", "relief", "takefocus", "text", "textvariable", "underline", "wraplength", ) OPTIONS_SPECIFIC = ("height", "state", "width") class_ = tk.Label container = False properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC register_widget("tk.Label", TKLabel, "Label", (_("Control & Display"), "tk")) class TKLabelFrame(BuilderObject): class_ = tk.LabelFrame container = True container_layout = True OPTIONS_STANDARD = ( "borderwidth", "cursor", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "padx", "pady", "relief", "takefocus", "text", ) OPTIONS_SPECIFIC = ( "background", "class_", "height", "labelanchor", "width", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC ro_properties = ("class_",) register_widget( "tk.LabelFrame", TKLabelFrame, "LabelFrame", (_("Containers"), "tk") ) class TKEntry(EntryBaseBO): OPTIONS_STANDARD = ( "background", "borderwidth", "cursor", "exportselection", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "insertbackground", "insertborderwidth", "insertofftime", "insertontime", "insertwidth", "justify", "relief", "selectbackground", "selectborderwidth", "selectforeground", "takefocus", "textvariable", "xscrollcommand", ) OPTIONS_SPECIFIC = ( "disabledbackground", "disabledforeground", "invalidcommand", "readonlybackground", "show", "state", "validate", "validatecommand", "width", ) OPTIONS_CUSTOM = ("text",) class_ = tk.Entry container = False properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC + OPTIONS_CUSTOM command_properties = ( "validatecommand", "invalidcommand", "xscrollcommand", ) register_widget("tk.Entry", TKEntry, "Entry", (_("Control & Display"), "tk")) class TKButton(BuilderObject): class_ = tk.Button container = False OPTIONS_STANDARD = ( "activebackground", "activeforeground", "anchor", "background", "bitmap", "borderwidth", "compound", "cursor", "disabledforeground", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "image", "justify", "padx", "pady", "relief", "repeatdelay", "repeatinterval", "takefocus", "text", "textvariable", "underline", "wraplength", ) OPTIONS_SPECIFIC = ( "command", "default", "height", "overrelief", "state", "width", ) properties = ( OPTIONS_STANDARD + OPTIONS_SPECIFIC + BuilderObject.OPTIONS_CUSTOM ) command_properties = ("command",) register_widget("tk.Button", TKButton, "Button", (_("Control & Display"), "tk")) class TKCheckbutton(BuilderObject): class_ = tk.Checkbutton container = False OPTIONS_STANDARD = ( "activebackground", "activeforeground", "anchor", "background", "bitmap", "borderwidth", "compound", "cursor", "disabledforeground", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "image", "justify", "padx", "pady", "relief", "takefocus", "text", "textvariable", "underline", "wraplength", ) OPTIONS_SPECIFIC = ( "command", "height", "indicatoron", "overrelief", "offrelief", "offvalue", "onvalue", "overrelief", "selectcolor", "selectimage", "state", "tristateimage", "tristatevalue", "variable", "width", ) properties = ( OPTIONS_STANDARD + OPTIONS_SPECIFIC + BuilderObject.OPTIONS_CUSTOM ) command_properties = ("command",) register_widget( "tk.Checkbutton", TKCheckbutton, "Checkbutton", (_("Control & Display"), "tk"), ) class TKRadiobutton(BuilderObject): class_ = tk.Radiobutton container = False OPTIONS_STANDARD = ( "activebackground", "activeforeground", "anchor", "background", "bitmap", "borderwidth", "compound", "cursor", "disabledforeground", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "image", "justify", "padx", "pady", "relief", "takefocus", "text", "textvariable", "underline", "wraplength", ) OPTIONS_SPECIFIC = ( "command", "height", "indicatoron", "overrelief", "offrelief", "overrelief", "selectcolor", "selectimage", "state", "tristateimage", "tristatevalue", "value", "variable", "width", ) properties = ( OPTIONS_STANDARD + OPTIONS_SPECIFIC + BuilderObject.OPTIONS_CUSTOM ) command_properties = ("command",) register_widget( "tk.Radiobutton", TKRadiobutton, "Radiobutton", (_("Control & Display"), "tk"), ) class TKListbox(BuilderObject): class_ = tk.Listbox container = False OPTIONS_STANDARD = ( "background", "borderwidth", "cursor", "disabledforeground", "exportselection", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "justify", "relief", "selectbackground", "selectborderwidth", "selectforeground", "setgrid", "takefocus", "xscrollcommand", "yscrollcommand", ) OPTIONS_SPECIFIC = ( "activestyle", "height", "listvariable", "selectmode", "state", "width", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ("xscrollcommand", "yscrollcommand") register_widget( "tk.Listbox", TKListbox, "Listbox", (_("Control & Display"), "tk") ) class TKText(BuilderObject): class_ = tk.Text container = False OPTIONS_STANDARD = ( "background", "borderwidth", "cursor", "exportselection", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "insertbackground", "insertborderwidth", "insertofftime", "insertontime", "insertwidth", "padx", "pady", "relief", "selectbackground", "selectborderwidth", "selectforeground", "setgrid", "takefocus", "xscrollcommand", "yscrollcommand", ) OPTIONS_SPECIFIC = ( "autoseparators", "blockcursor", "endline", "height", "inactiveselectbackground", "insertunfocussed", "maxundo", "spacing1", "spacing2", "spacing3", "startline", "state", "tabs", "tabstyle", "undo", "width", "wrap", ) OPTIONS_CUSTOM = ("text",) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC + OPTIONS_CUSTOM command_properties = ("xscrollcommand", "yscrollcommand") def _set_property(self, target_widget, pname, value): if pname == "text": state = target_widget.cget("state") if state == tk.DISABLED: target_widget.configure(state=tk.NORMAL) target_widget.insert("0.0", value) target_widget.configure(state=tk.DISABLED) else: target_widget.insert("0.0", value) else: super(TKText, self)._set_property(target_widget, pname, value) # # Code generation methods # def _code_set_property(self, targetid, pname, value, code_bag): if pname == "text": state_value = "" if "state" in self.wmeta.properties: state_value = self.wmeta.properties["state"] sval = self.builder.code_translate_str(value) lines = [ f"_text_ = {sval}", ] if state_value == tk.DISABLED: lines.extend( ( f'{targetid}.configure(state="normal")', f'{targetid}.insert("0.0", _text_)', f'{targetid}.configure(state="disabled")', ) ) else: lines.append(f'{targetid}.insert("0.0", _text_)') code_bag[pname] = lines else: super(TKText, self)._code_set_property( targetid, pname, value, code_bag ) register_widget( "tk.Text", TKText, "Text", (_("Control & Display"), "tk", "ttk") ) class TKPanedWindow(PanedWindowBO): class_ = tk.PanedWindow allowed_children = ("tk.PanedWindow.Pane",) OPTIONS_STANDARD = ( "background", "borderwidth", "cursor", "orient", "relief", ) OPTIONS_SPECIFIC = ( "handlepad", "handlesize", "height", "opaqueresize", "proxybackground", "proxyborderwidth", "proxyrelief", "sashcursor", "sashpad", "sashrelief", "sashwidth", "showhandle", "width", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC register_widget( "tk.PanedWindow", TKPanedWindow, "PanedWindow", (_("Containers"), "tk") ) class TKMenubutton(BuilderObject): class_ = tk.Menubutton container = False OPTIONS_STANDARD = ( "activebackground", "activeforeground", "anchor", "background", "bitmap", "borderwidth", "compound", "cursor", "disabledforeground", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "image", "justify", "padx", "pady", "relief", "takefocus", "text", "textvariable", "underline", "wraplength", ) OPTIONS_SPECIFIC = ( "direction", "height", "indicatoron", "state", "width", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC allowed_children = ("tk.Menu",) maxchildren = 1 def add_child(self, bobject): self.widget.configure(menu=bobject.widget) def code_child_add(self, childid): lines = [f"{self.code_identifier()}.configure(menu={childid})"] return lines register_widget( "tk.Menubutton", TKMenubutton, "Menubutton", ( _("Menu"), _("Control & Display"), "tk", ), ) class TKMessage(BuilderObject): class_ = tk.Message container = False OPTIONS_STANDARD = ( "anchor", "background", "borderwidth", "cursor", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "padx", "pady", "relief", "takefocus", "text", "textvariable", ) OPTIONS_SPECIFIC = ("aspect", "justify", "width") properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC register_widget( "tk.Message", TKMessage, "Message", (_("Control & Display"), "tk", "ttk") ) class TKScale(BuilderObject): class_ = tk.Scale container = False OPTIONS_STANDARD = ( "activebackground", "background", "borderwidth", "cursor", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "orient", "relief", "repeatdelay", "repeatinterval", "takefocus", "troughcolor", ) OPTIONS_SPECIFIC = ( "bigincrement", "command", "digits", "from_", "label", "length", "resolution", "showvalue", "sliderlength", "sliderrelief", "state", "tickinterval", "to", "variable", "width", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ("command",) register_widget("tk.Scale", TKScale, "Scale", (_("Control & Display"), "tk")) class TKScrollbar(BuilderObject): class_ = tk.Scrollbar container = False OPTIONS_STANDARD = ( "activebackground", "background", "borderwidth", "cursor", "highlightbackground", "highlightcolor", "highlightthickness", "jump", "orient", "relief", "repeatdelay", "repeatinterval", "takefocus", "troughcolor", ) OPTIONS_SPECIFIC = ( "activerelief", "command", "elementborderwidth", "width", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ("command",) register_widget( "tk.Scrollbar", TKScrollbar, "Scrollbar", (_("Control & Display"), "tk") ) class TKSpinbox(BuilderObject): class_ = tk.Spinbox container = False OPTIONS_STANDARD = ( "activebackground", "background", "borderwidth", "cursor", "exportselection", "font", "foreground", "highlightbackground", "highlightcolor", "highlightthickness", "insertbackground", "insertborderwidth", "insertofftime", "insertontime", "insertwidth", "justify", "relief", "repeatdelay", "repeatinterval", "selectbackground", "selectborderwidth", "selectforeground", "takefocus", "textvariable", "xscrollcommand", ) OPTIONS_SPECIFIC = ( "buttonbackground", "buttoncursor", "buttondownrelief", "buttonuprelief", "command", "disabledbackground", "disabledforeground", "format", "from_", "invalidcommand", "increment", "readonlybackground", "state", "to", "validate", "validatecommand", "values", "width", "wrap", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ( "command", "invalidcommand", "validatecommand", "xscrollcommand", ) def _set_property(self, target_widget, pname, value): # hack to configure 'from_' and 'to' and avoid exception if pname == "from_": from_ = float(value) to = float(self.wmeta.properties.get("to", 0)) if from_ > to: to = from_ + 1 target_widget.configure(from_=from_, to=to) else: super(TKSpinbox, self)._set_property(target_widget, pname, value) register_widget( "tk.Spinbox", TKSpinbox, "Spinbox", (_("Control & Display"), "tk") ) class TKCanvas(BuilderObject): class_ = tk.Canvas container = False OPTIONS_STANDARD = ( "background", "borderwidth", "cursor", "highlightbackground", "highlightcolor", "highlightthickness", "insertbackground", "insertborderwidth", "insertofftime", "insertontime", "insertwidth", "relief", "selectbackground", "selectborderwidth", "selectforeground", "takefocus", "xscrollcommand", "yscrollcommand", ) OPTIONS_SPECIFIC = ( "closeenough", "confine", "height", "scrollregion", "state", "width", "xscrollincrement", "yscrollincrement", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ("xscrollcommand", "yscrollcommand") register_widget( "tk.Canvas", TKCanvas, "Canvas", (_("Control & Display"), "tk", "ttk") ) class TKMenu(BuilderObject): layout_required = False allowed_parents = ( "root", "tk.Menubutton", "ttk.Menubutton", "pygubu.builder.widgets.toplevelmenu", ) allowed_children = ( "tk.Menuitem.Submenu", "tk.Menuitem.Checkbutton", "tk.Menuitem.Command", "tk.Menuitem.Radiobutton", "tk.Menuitem.Separator", ) class_ = tk.Menu container = True OPTIONS_STANDARD = ( "activebackground", "activeborderwidth", "activeforeground", "background", "borderwidth", "cursor", "disabledforeground", "font", "foreground", "relief", "takefocus", ) OPTIONS_SPECIFIC = ( "postcommand", "selectcolor", "tearoff", "tearoffcommand", "title", ) properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ("postcommand", "tearoffcommand") allow_bindings = False def __init__(self, builder, wdescr): super().__init__(builder, wdescr) self._menuitems = None def layout(self, target=None): pass # # code generation functions # def add_menuitem(self, itemid, itemtype, properties): if self._menuitems is None: self._menuitems = [] self._menuitems.append((itemtype, properties)) def code_realize(self, boparent, code_identifier=None): start = -1 tearoff_conf = self.wmeta.properties.get("tearoff", "true") if tearoff_conf in ("1", "true"): start = 0 self.code_item_index = start return super(TKMenu, self).code_realize(boparent, code_identifier) def _code_define_callback_args(self, cmd_pname, cmd): args = None if cmd_pname == "tearoffcommand": args = ("menu", "tearoff") return args def code_configure_children(self, targetid=None): if self._menuitems is None: return tuple() if targetid is None: targetid = self.code_identifier() lines = [] for itemtype, kwp in self._menuitems: bag = [] for pname, value in kwp.items(): s = f"{pname}={value}" bag.append(s) props = "" if bag: props = ", " + ", ".join(bag) line = f'{targetid}.add("{itemtype}"{props})' lines.append(line) return lines register_widget("tk.Menu", TKMenu, "Menu", (_("Menu"), "tk", "ttk")) # # Helpers for Standard tk widgets # class TKMenuitem(BuilderObject): class_ = None container = False itemtype = None layout_required = False OPTIONS_STANDARD = ( "activebackground", "activeforeground", "background", "bitmap", "compound", "foreground", "state", ) OPTIONS_SPECIFIC = ( "accelerator", "columnbreak", "command", "font", "hidemargin", "image", "label", "underline", ) properties = ( OPTIONS_STANDARD + OPTIONS_SPECIFIC + BuilderObject.OPTIONS_CUSTOM ) command_properties = ("command",) allow_bindings = False def realize(self, parent): self.widget = master = parent.get_child_master() itemproperties = dict(self.wmeta.properties) self._setup_item_properties(itemproperties) master.add(self.itemtype, **itemproperties) self._setup_item_index(parent) return self.widget def _setup_item_index(self, parent): master = parent.get_child_master() index = master.index(tk.END) or 0 # TODO: index of items is shifted if tearoff is changed # for now check tearoff config and recalculate index. has_tearoff = True if master.type(0) == "tearoff" else False tearoff_conf = parent.wmeta.properties.get("tearoff", "1") offset = 0 if has_tearoff and tearoff_conf in ("0", "false"): offset = 1 self.__index = index - offset def _setup_item_properties(self, itemprops): for pname in itemprops: if pname == "variable": varname = itemprops[pname] itemprops[pname] = self.builder.create_variable(varname) if pname in ("image", "selectimage"): name = itemprops[pname] itemprops[pname] = self.builder.get_image(name) def configure(self): pass def layout(self, target=None): pass def _connect_command(self, cpname, callback): self.widget.entryconfigure(self.__index, command=callback) # # code generation functions # def code_realize(self, boparent, code_identifier=None): self._code_identifier = boparent.code_child_master() ( code_bag, kwproperties, complex_properties, ) = self._code_process_properties( self.wmeta.properties, self._code_identifier, skip_commands=False ) properties = {} for pname in kwproperties: properties[pname] = code_bag[pname] boparent.add_menuitem(self.wmeta.identifier, self.itemtype, properties) lines = [] for pname in complex_properties: lines.extend(code_bag[pname]) return lines def code_configure(self, targetid=None): return tuple() def _code_set_property(self, targetid, pname, value, code_bag): if pname == "command_id_arg": # pass, property for command configuration pass else: super(TKMenuitem, self)._code_set_property( targetid, pname, value, code_bag ) def _pass_widgetid_to_callback(self): include_id = self.wmeta.properties.get( "command_id_arg", "false" ).lower() return include_id == "true" def _code_define_callback_args(self, cmd_pname, cmd): cmdtype = cmd["cbtype"] args = None if cmdtype == CB_TYPES.WITH_WID or self._pass_widgetid_to_callback(): args = ("itemid",) return args def _code_define_callback(self, cmd_pname, cmd): usercb = super()._code_define_callback(cmd_pname, cmd) self._realcb = usercb args = self._code_define_callback_args(cmd_pname, cmd) if args is not None and "itemid" in args: usercb = f"{self.wmeta.identifier}_cmd" return usercb def _code_connect_item_command(self, cmd_pname, cmd, cbname): lines = [] if cbname != self._realcb: cbname = self._realcb newcb = f"{self.wmeta.identifier}_cmd" wid = self.wmeta.identifier line = f'def {newcb}(itemid="{wid}"): {cbname}(itemid)' lines.append(line) return lines def _code_connect_command(self, cmd_pname, cmd, cbname): if self.itemtype != "submenu": return self._code_connect_item_command(cmd_pname, cmd, cbname) else: return super(TKMenuitem, self)._code_connect_command( cmd_pname, cmd, cbname ) class TKMenuitemSubmenu(TKMenuitem): itemtype = "submenu" allowed_parents = ("tk.Menu", "tk.Menuitem.Submenu") allowed_children = ( "tk.Menuitem.Submenu", "tk.Menuitem.Checkbutton", "tk.Menuitem.Command", "tk.Menuitem.Radiobutton", "tk.Menuitem.Separator", ) OPTIONS_STANDARD = ( "activebackground", "activeborderwidth", "activeforeground", "background", "borderwidth", "bitmap", "compound", "cursor", "disabledforeground", "font", "foreground", "relief", "takefocus", "state", ) OPTIONS_SPECIFIC = ( "accelerator", "columnbreak", "hidemargin", "image", "label", "selectcolor", "tearoff", "tearoffcommand", "underline", "postcommand", ) OPTIONS_CUSTOM = ("specialmenu",) properties = tuple( set(OPTIONS_STANDARD + OPTIONS_SPECIFIC + OPTIONS_CUSTOM) ) # ro_properties = ('specialmenu', ) command_properties = ("postcommand", "tearoffcommand") def __init__(self, builder, wdescr): super().__init__(builder, wdescr) self._menuitems = None def realize(self, parent): master = parent.get_child_master() self._setup_item_index(parent) menu_properties = dict( (k, v) for k, v in self.wmeta.properties.items() if k in TKMenu.properties or k == "specialmenu" ) self._setup_item_properties(menu_properties) item_properties = dict( (k, v) for k, v in self.wmeta.properties.items() if k in TKMenuitem.properties ) self._setup_item_properties(item_properties) self.widget = submenu = TKMenu.class_(master, **menu_properties) item_properties["menu"] = submenu master.add(tk.CASCADE, **item_properties) return self.widget def _setup_item_properties(self, itemprops): super(TKMenuitemSubmenu, self)._setup_item_properties(itemprops) pname = "specialmenu" if pname in itemprops: specialmenu = itemprops.pop(pname) itemprops["name"] = specialmenu def configure(self): pass def layout(self, target=None): pass def _connect_command(self, cpname, callback): # suported commands: tearoffcommand, postcommand kwargs = {cpname: callback} self.widget.configure(**kwargs) # # code generation functions # def add_menuitem(self, itemid, itemtype, properties): if self._menuitems is None: self._menuitems = [] self._menuitems.append((itemtype, properties)) def code_realize(self, boparent, code_identifier=None): self._code_identifier = code_identifier masterid = boparent.code_child_master() lines = [] # menu properties menuprop = {} for pname, value in self.wmeta.properties.items(): if pname in TKMenu.properties: menuprop[pname] = value if pname == "specialmenu": menuprop["name"] = value ( code_bag, kw_properties, complex_properties, ) = self._code_process_properties(menuprop, self.code_identifier()) for pname in complex_properties: lines.extend(code_bag[pname]) mpbag = [] for pname in kw_properties: line = "{0}={1}".format(pname, code_bag[pname]) mpbag.append(line) mprops = "" if mpbag: mprops = ", " + ", ".join(mpbag) # item properties itemprop = {} for pname, value in self.wmeta.properties.items(): if pname in TKMenuitem.properties: itemprop[pname] = value ( code_bag, kw_properties, complex_properties, ) = self._code_process_properties(itemprop, self.code_identifier()) for pname in complex_properties: lines.extend(code_bag[pname]) pbag = [] prop = "menu={0}".format(self.code_identifier()) pbag.append(prop) for pname in kw_properties: line = "{0}={1}".format(pname, code_bag[pname]) pbag.append(line) props = "" if pbag: props = ", {0}".format(", ".join(pbag)) # creation line = "{0} = tk.Menu({1}{2})".format( self.code_identifier(), masterid, mprops ) lines.append(line) line = "{0}.add(tk.CASCADE{1})".format(masterid, props) lines.append(line) return lines def code_configure(self, targetid=None): return tuple() def code_configure_children(self, targetid=None): if self._menuitems is None: return tuple() if targetid is None: targetid = self.code_identifier() lines = [] for itemtype, kwp in self._menuitems: bag = [] for pname, value in kwp.items(): s = f"{pname}={value}" bag.append(s) props = "" if bag: props = ", " + ", ".join(bag) line = f'{targetid}.add("{itemtype}"{props})' lines.append(line) return lines def _code_define_callback_args(self, cmd_pname, cmd): args = None if cmd_pname == "tearoffcommand": args = ("menu", "tearoff") return args register_widget( "tk.Menuitem.Submenu", TKMenuitemSubmenu, "Menuitem.Submenu", (_("Menu"), "tk", "ttk"), ) class TKMenuitemCommand(TKMenuitem): allowed_parents = ("tk.Menu", "tk.Menuitem.Submenu") itemtype = tk.COMMAND register_widget( "tk.Menuitem.Command", TKMenuitemCommand, "Menuitem.Command", (_("Menu"), "tk", "ttk"), ) class TKMenuitemCheckbutton(TKMenuitem): allowed_parents = ("tk.Menu", "tk.Menuitem.Submenu") itemtype = tk.CHECKBUTTON OPTIONS_STANDARD = TKMenuitem.OPTIONS_STANDARD OPTIONS_SPECIFIC = TKMenuitem.OPTIONS_SPECIFIC + ( "indicatoron", "onvalue", "offvalue", "selectcolor", "selectimage", "variable", ) OPTIONS_CUSTOM = TKMenuitem.OPTIONS_CUSTOM properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC + OPTIONS_CUSTOM register_widget( "tk.Menuitem.Checkbutton", TKMenuitemCheckbutton, "Menuitem.Checkbutton", (_("Menu"), "tk", "ttk"), ) class TKMenuitemRadiobutton(TKMenuitem): allowed_parents = ("tk.Menu", "tk.Menuitem.Submenu") itemtype = tk.RADIOBUTTON OPTIONS_STANDARD = TKMenuitem.OPTIONS_STANDARD OPTIONS_SPECIFIC = TKMenuitem.OPTIONS_SPECIFIC + ( "indicatoron", "selectcolor", "selectimage", "value", "variable", ) OPTIONS_CUSTOM = TKMenuitem.OPTIONS_CUSTOM properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC + OPTIONS_CUSTOM register_widget( "tk.Menuitem.Radiobutton", TKMenuitemRadiobutton, "Menuitem.Radiobutton", (_("Menu"), "tk", "ttk"), ) class TKMenuitemSeparator(TKMenuitem): allowed_parents = ("tk.Menu", "tk.Menuitem.Submenu") itemtype = tk.SEPARATOR OPTIONS_STANDARD = ("background",) OPTIONS_SPECIFIC = tuple() OPTIONS_CUSTOM = tuple() properties = tuple() command_properties = tuple() register_widget( "tk.Menuitem.Separator", TKMenuitemSeparator, "Menuitem.Separator", (_("Menu"), "tk", "ttk"), ) class TKPanedWindowPane(PanedWindowPaneBO): class_ = None container = True allowed_parents = ("tk.PanedWindow",) maxchildren = 1 OPTIONS_SPECIFIC = ( "height", "hide", "minsize", "padx", "pady", "sticky", "stretch", "width", ) properties = OPTIONS_SPECIFIC register_widget( "tk.PanedWindow.Pane", TKPanedWindowPane, "PanedWindow.Pane", (_("Pygubu Helpers"), "tk"), ) class TKLabelwidgetBO(BuilderObject): class_ = None container = True allowed_parents = ("tk.LabelFrame", "ttk.Labelframe") maxchildren = 1 layout_required = False allow_bindings = False def realize(self, parent): self.widget = parent.get_child_master() return self.widget def add_child(self, bobject): self.widget.configure(labelwidget=bobject.widget) def layout(self, target=None): pass # # code generation functions # def code_realize(self, boparent, code_identifier=None): self._code_identifier = boparent.code_child_master() return tuple() def code_configure(self, targetid=None): return tuple() def code_layout(self, targetid=None, parentid=None): return tuple() def code_child_add(self, childid): line = "{0}.configure(labelwidget={1})" line = line.format(self.code_child_master(), childid) return (line,) register_widget( "pygubu.builder.widgets.Labelwidget", TKLabelwidgetBO, "Labelwidget", (_("Pygubu Helpers"), "tk", "ttk"), ) class ToplevelMenuHelperBO(BuilderObject): class_ = None container = True allowed_parents = ("tk.Toplevel",) maxchildren = 1 layout_required = False allow_bindings = False def realize(self, parent): self.widget = parent.get_child_master() return self.widget def add_child(self, bobject): self.widget.configure(menu=bobject.widget) def layout(self, target=None): pass # # code generation functions # def code_realize(self, boparent, code_identifier=None): self._code_identifier = boparent.code_child_master() return tuple() def code_configure(self, targetid=None): return tuple() def code_layout(self, targetid=None, parentid=None): return tuple() def code_child_add(self, childid): line = "{0}.configure(menu={1})" line = line.format(self.code_child_master(), childid) return (line,) register_widget( "pygubu.builder.widgets.toplevelmenu", ToplevelMenuHelperBO, "ToplevelMenu", (_("Menu"), _("Pygubu Helpers"), "tk", "ttk"), ) class TKOptionMenu(BuilderObject): class_ = tk.OptionMenu OPTIONS_STANDARD = tuple() OPTIONS_SPECIFIC = ("command", "variable", "value", "values") properties = OPTIONS_STANDARD + OPTIONS_SPECIFIC command_properties = ("command",) ro_properties = ("variable", "value", "values") def realize(self, parent): args = self._get_init_args() master = parent.get_child_master() variable = args.pop("variable", None) value = args.pop("value", None) if variable is None: varname = "{0}__var".format(self.wmeta.identifier) variable = self.builder.create_variable(varname) if value is not None: variable.set(value) values = args.pop("values", "") if values is not None: values = values.split(",") class _cb_proxy(object): def __init__(self): super(_cb_proxy, self).__init__() self.callback = None def __call__(self, arg1): if self.callback is not None: self.callback(arg1) cb_proxy = _cb_proxy() self.widget = self.class_(master, variable, *values, command=cb_proxy) self.widget._cb_proxy = cb_proxy return self.widget def _connect_command(self, cmd_pname, callback): if cmd_pname == "command": self.widget._cb_proxy.callback = callback # # Code generation methods # def code_realize(self, boparent, code_identifier=None): import json if code_identifier is not None: self._code_identifier = code_identifier lines = [] master = boparent.code_child_master() init_args = self._code_get_init_args(self.code_identifier()) command_arg = None variable_arg = None # value_arg = None # command property pname = "command" if pname in self.wmeta.properties: value = json.loads(self.wmeta.properties[pname]) cmdname = value["value"] cmdtype = value["type"] args = ("option",) pvalue = self.builder.code_create_callback( self.code_identifier(), cmdname, cmdtype, args ) command_arg = f"{pvalue}" # Value property # Not used in code generation. # Already setup in _code_get_init_args # Variable property pname = "variable" varname = "__tkvar" if pname in init_args: varname = init_args[pname] variable_arg = varname # values property pname = "values" om_values = [] if pname in self.wmeta.properties: value = self.wmeta.properties["values"] om_values = value.split(",") line = f"__values = {om_values}" lines.append(line) s = f"{self.code_identifier()} = {self._code_class_name()}({master}, {variable_arg}, *__values, command={command_arg})" lines.append(s) return lines def code_configure(self, targetid=None): return [] def code_connect_commands(self): return [] register_widget( "tk.OptionMenu", TKOptionMenu, "OptionMenu", (_("Control & Display"), "tk", "ttk"), )
mit
a7da727d098caee4440e1d8e0aee0576
24.902913
127
0.545259
3.959558
false
false
false
false
alejandroautalan/pygubu
src/pygubu/plugins/customtkinter/designer/designerplugin.py
1
2144
from pygubu.api.v1 import IPluginBase, IDesignerPlugin from .preview import CTkToplevelPreviewBO, CTkPreviewBO, CTkFramePreviewBO from ..ctkbase import _plugin_uid class CTkDesignerPlugin(IDesignerPlugin): def get_preview_builder(self, builder_uid: str): if builder_uid == f"{_plugin_uid}.CTkToplevel": return CTkToplevelPreviewBO if builder_uid == f"{_plugin_uid}.CTk": return CTkPreviewBO if builder_uid == f"{_plugin_uid}.CTkFrame": return CTkFramePreviewBO return None def get_toplevel_preview_for( self, builder_uid: str, widget_id: str, builder, top_master ): top = None toplevel_uids = ("customtkinter.CTkToplevel", "customtkinter.CTk") if builder_uid in toplevel_uids: top = builder.get_object(widget_id) return top def configure_for_preview(self, builder_uid: str, widget): """Make widget just display with minimal functionality.""" def _no_op(event=None): pass if builder_uid.endswith(".CTKEntry"): seqlist = ("<FocusOut>", "<FocusIn>") for seq in seqlist: widget.canvas.bind(seq, _no_op) elif builder_uid.endswith(".CTkSlider"): seqlist = ("<Enter>", "<Leave>", "<Button-1>", "<B1-Motion>") for seq in seqlist: widget.canvas.bind(seq, _no_op) elif builder_uid.endswith(".CTkOptionMenu"): seqlist = ("<Enter>", "<Leave>", "<Button-1>") for seq in seqlist: widget.canvas.bind(seq, _no_op) widget.text_label.bind(seq, _no_op) elif builder_uid.endswith(".CTkComboBox"): widget.canvas.tag_bind("right_parts", "<Enter>", _no_op) widget.canvas.tag_bind("dropdown_arrow", "<Enter>", _no_op) widget.canvas.tag_bind("right_parts", "<Leave>", _no_op) widget.canvas.tag_bind("dropdown_arrow", "<Leave>", _no_op) widget.canvas.tag_bind("right_parts", "<Button-1>", _no_op) widget.canvas.tag_bind("dropdown_arrow", "<Button-1>", _no_op)
mit
13a887e73b52613675378865ddd0e922
41.88
74
0.589086
3.621622
false
false
false
false
alejandroautalan/pygubu
src/pygubu/widgets/dialog.py
1
4608
# encoding: UTF-8 import tkinter as tk import tkinter.ttk as ttk class Dialog(object): """ Virtual events: <<DialogClose>> """ def __init__(self, parent, modal=False): self.parent = parent self.is_modal = modal self.show_centered = True self.running_modal = False self.toplevel = tk.Toplevel(parent) self.toplevel.withdraw() self.toplevel.protocol("WM_DELETE_WINDOW", self._on_wm_delete_window) self.bind("<<DialogClose>>", self._default_close_action) self._init_before() self._create_ui() self._init_after() # self.frame.pack(fill='both', expand=True) def _init_before(self): pass def _create_ui(self): pass def _init_after(self): pass def set_modal(self, modal): self.is_modal = modal def center_window(self): """Center a window on its parent or screen.""" window = self.toplevel height = window.winfo_height() width = window.winfo_width() parent = self.parent if parent: x_coord = int( parent.winfo_x() + (parent.winfo_width() / 2 - width / 2) ) y_coord = int( parent.winfo_y() + (parent.winfo_height() / 2 - height / 2) ) else: x_coord = int(window.winfo_screenwidth() / 2 - width / 2) y_coord = int(window.winfo_screenheight() / 2 - height / 2) geom = "{0}x{1}+{2}+{3}".format(width, height, x_coord, y_coord) window.geometry(geom) def run(self): self.toplevel.transient(self.parent) self.toplevel.deiconify() self.toplevel.wait_visibility() if self.show_centered: self.center_window() initial_focus = self.toplevel.focus_lastfor() if initial_focus: initial_focus.focus_set() if self.is_modal: self.running_modal = True self.toplevel.grab_set() def destroy(self): if self.toplevel: self.toplevel.destroy() self.toplevel = None def _on_wm_delete_window(self): self.toplevel.event_generate("<<DialogClose>>") def _default_close_action(self, dialog): self.close() def close(self): if self.running_modal: self.toplevel.grab_release() self.running_modal = False self.toplevel.withdraw() self.parent.focus_set() def show(self): if self.toplevel: self.toplevel.deiconify() def set_title(self, title): """Sets the dialog title""" if self.toplevel: self.toplevel.title(title) # # interface to toplevel methods used by gui builder # def configure(self, cnf=None, **kw): if "modal" in kw: value = kw.pop("modal") self.set_modal(tk.getboolean(value)) self.toplevel.configure(cnf, **kw) config = configure def cget(self, key): if key == "modal": return self.is_modal return self.toplevel.cget(key) __getitem__ = cget def __setitem__(self, key, value): self.configure({key: value}) def bind(self, sequence=None, func=None, add=None): def dialog_cb(event, dialog=self): func(dialog) return self.toplevel.bind(sequence, dialog_cb, add) # def unbind(self, sequence, funcid=None): # pass if __name__ == "__main__": class TestDialog(Dialog): def _create_ui(self): label = ttk.Label(self.frame, text="TestDialog Class") label.pack() entry = ttk.Entry(self.frame) entry.pack() # f = ttk.Frame(self.toplevel) # self.default_buttonbox(f) # f.pack(fill='x') app = tk.Tk() dialog = None def show_dialog(): global dialog if dialog is None: dialog = TestDialog(app) dialog.run() else: dialog.show() def custom_callback(dialog): print("Custom callback") dialog.close() def show_modal_dialog(): dialog = TestDialog(app) dialog.set_title("Modal dialog") dialog.set_modal(True) dialog.bind("<<DialogClose>>", custom_callback) print("before run") dialog.run() print("after run") btn = tk.Button(app, text="show dialog", command=show_dialog) btn.pack() btn = tk.Button(app, text="show modal dialog", command=show_modal_dialog) btn.pack() app.mainloop()
mit
c09904aec8a7351eb4d2725ac9be842e
25.635838
77
0.551649
3.836803
false
false
false
false
alejandroautalan/pygubu
src/pygubu/plugins/awesometkinter/scrollbar.py
1
1317
from pygubu.i18n import _ from pygubu.api.v1 import register_widget, register_custom_property from pygubu.plugins.ttk.ttkstdwidgets import TTKScrollbar import awesometkinter as atk from ..awesometkinter import _designer_tab_label, _plugin_uid class SimpleScrollbarBO(TTKScrollbar): OPTIONS_STANDARD = tuple( set(TTKScrollbar.OPTIONS_STANDARD) - set(("style",)) ) OPTIONS_CUSTOM = ("bg", "slider_color", "width") properties = ( OPTIONS_STANDARD + TTKScrollbar.OPTIONS_SPECIFIC + OPTIONS_CUSTOM ) ro_properties = TTKScrollbar.ro_properties + OPTIONS_CUSTOM + ("orient",) class_ = atk.scrollbar.SimpleScrollbar def _process_property_value(self, pname, value): if pname in ("width",): value_ = 5 try: value_ = int(value) except ValueError: pass return value_ return super()._process_property_value(pname, value) _builder_uid = _plugin_uid + ".SimpleScrollbar" register_widget( _builder_uid, SimpleScrollbarBO, "SimpleScrollbar", ("ttk", _designer_tab_label), ) register_custom_property(_builder_uid, "bg", "colorentry") register_custom_property(_builder_uid, "slider_color", "colorentry") register_custom_property(_builder_uid, "width", "naturalnumber")
mit
fd467eb4243744a5bc109c48c0e54a71
31.121951
77
0.666667
3.540323
false
false
false
false
alejandroautalan/pygubu
src/pygubu/plugins/tkintertable/table.py
1
4670
import tkinter as tk from pygubu.i18n import _ from pygubu.api.v1 import ( BuilderObject, register_widget, register_custom_property, ) from pygubu.utils.font import tkfontstr_to_tuple from tkintertable import TableCanvas from ..tkintertable import _designer_tab_label, _plugin_uid class TableCanvasBuilder(BuilderObject): class_ = TableCanvas OPTIONS_CUSTOM = ( "read_only", "width", "height", "bgcolor", "fgcolor", "rows", "cols", "cellwidth", "maxcellwidth", "rowheight", "horizlines", "vertlines", "alternaterows", "autoresizecols", "linewidth", "rowheaderwidth", "showkeynamesinheader", "thefont", "entrybackgr", "grid_color", "selectedcolor", "rowselectedcolor", "multipleselectioncolor", ) ro_properties = OPTIONS_CUSTOM layout_required = False def _process_property_value(self, pname, value): if pname in ( "rows", "cols", "cellwidth", "maxcellwidth", "rowheight", "rowheaderwidth", ): value = int(value) elif pname == "linewidth": value = float(value) elif pname in ("read_only", "showkeynamesinheader"): value = tk.getboolean(value) elif pname == "thefont": value = tkfontstr_to_tuple(value) elif pname in ( "horizlines", "vertlines", "alternaterows", "autoresizecols", ): value = int(tk.getboolean(value)) return value def layout(self, target=None, configure_gridrc=True): self.widget.show() def code_layout(self, targetid=None, parentid=None): if targetid is None: targetid = self.code_identifier() return [f"{targetid}.show()"] def _code_process_property_value(self, targetid, pname, value: str): pvalue = self._process_property_value(pname, value) if pname in ("thefont", "showkeynamesinheader"): return pvalue pvalue = f"{pvalue}" return super()._code_process_property_value(targetid, pname, pvalue) _builder_uid = f"{_plugin_uid}.TableCanvas" register_widget( _builder_uid, TableCanvasBuilder, "TableCanvas", ("ttk", _designer_tab_label), ) register_custom_property( _builder_uid, "read_only", "choice", values=("", "true", "false"), state="readonly", ) register_custom_property( _builder_uid, "width", "dimensionentry", ) register_custom_property( _builder_uid, "height", "dimensionentry", ) register_custom_property( _builder_uid, "bgcolor", "colorentry", ) register_custom_property( _builder_uid, "fgcolor", "colorentry", ) register_custom_property( _builder_uid, "rows", "naturalnumber", ) register_custom_property( _builder_uid, "cols", "naturalnumber", ) register_custom_property( _builder_uid, "cellwidth", "naturalnumber", ) register_custom_property( _builder_uid, "maxcellwidth", "naturalnumber", ) register_custom_property( _builder_uid, "rowheight", "naturalnumber", ) register_custom_property( _builder_uid, "horizlines", "choice", values=("", "true", "false"), state="readonly", ) register_custom_property( _builder_uid, "vertlines", "choice", values=("", "true", "false"), state="readonly", ) register_custom_property( _builder_uid, "alternaterows", "choice", values=("", "true", "false"), state="readonly", ) register_custom_property( _builder_uid, "autoresizecols", "choice", values=("", "true", "false"), state="readonly", ) register_custom_property( _builder_uid, "linewidth", "realnumber", ) register_custom_property( _builder_uid, "rowheaderwidth", "naturalnumber", ) register_custom_property( _builder_uid, "showkeynamesinheader", "choice", values=("", "true", "false"), state="readonly", ) register_custom_property( _builder_uid, "thefont", "fontentry", ) register_custom_property( _builder_uid, "entrybackgr", "colorentry", ) register_custom_property( _builder_uid, "grid_color", "colorentry", ) register_custom_property( _builder_uid, "selectedcolor", "colorentry", ) register_custom_property( _builder_uid, "rowselectedcolor", "colorentry", ) register_custom_property( _builder_uid, "multipleselectioncolor", "colorentry", )
mit
303783f41a3309963fc2160677dfe8aa
20.422018
76
0.59015
3.570336
false
false
false
false
alejandroautalan/pygubu
src/pygubu/plugins/awesometkinter/frame.py
1
3054
""" Documentation, License etc. @package pygubu.plugins.awesometkinter """ import tkinter as tk from pygubu.i18n import _ from pygubu.api.v1 import register_widget, register_custom_property from pygubu.plugins.tk.tkstdwidgets import TKFrame from pygubu.plugins.ttk.ttkstdwidgets import TTKFrame import awesometkinter as atk from ..awesometkinter import _designer_tab_label, _plugin_uid class Frame3dBO(TTKFrame): OPTIONS_STANDARD = tuple(set(TTKFrame.OPTIONS_STANDARD) - set(("style",))) OPTIONS_CUSTOM = ("bg",) properties = OPTIONS_STANDARD + TTKFrame.OPTIONS_SPECIFIC + OPTIONS_CUSTOM ro_properties = TTKFrame.ro_properties + ("bg",) class_ = atk.Frame3d _builder_uid = _plugin_uid + ".Frame3d" register_widget( _builder_uid, Frame3dBO, "Frame3d", ("ttk", _designer_tab_label), group=0 ) register_custom_property( _builder_uid, "bg", "colorentry", help=_("color of frame") ) class ScrollableFrameBO(TKFrame): OPTIONS_STANDARD = tuple() OPTIONS_SPECIFIC = tuple() OPTIONS_CUSTOM = ( "vscroll", "hscroll", "autoscroll", "bg", "sbar_fg", "sbar_bg", "vbar_width", "hbar_width", ) ro_properties = OPTIONS_CUSTOM class_ = atk.ScrollableFrame def _process_property_value(self, pname, value): if pname in ("vscroll", "hscroll", "autoscroll"): return tk.getboolean(value) return super()._process_property_value(pname, value) def _code_process_property_value(self, targetid, pname, value): if pname in ("vscroll", "hscroll", "autoscroll"): return tk.getboolean(value) return super()._code_process_property_value(targetid, pname, value) _builder_uid = _plugin_uid + ".ScrollableFrame" register_widget( _builder_uid, ScrollableFrameBO, "ScrollableFrame", ("ttk", _designer_tab_label), group=0, ) register_custom_property( _builder_uid, "vscroll", "choice", values=("", "false", "true"), state="readonly", help=_("use vertical scrollbar"), ) register_custom_property( _builder_uid, "hscroll", "choice", values=("", "false", "true"), state="readonly", help=_("use horizontal scrollbar"), ) register_custom_property( _builder_uid, "autoscroll", "choice", values=("", "false", "true"), state="readonly", help=_("auto scroll to bottom if new items added to frame"), ) register_custom_property( _builder_uid, "bg", "colorentry", help=_("background color") ) register_custom_property( _builder_uid, "sbar_fg", "colorentry", help=_("color of scrollbars' slider") ) register_custom_property( _builder_uid, "sbar_bg", "colorentry", help=_("color of scrollbars' trough, default to frame's background"), ) register_custom_property( _builder_uid, "vbar_width", "dimensionentry", help=_("vertical scrollbar width"), ) register_custom_property( _builder_uid, "hbar_width", "dimensionentry", help=_("vertical scrollbar width"), )
mit
292ed28182080b64aad08c13aa22bb6a
23.629032
80
0.647348
3.345016
false
false
false
false
yashaka/selene
examples/log_all_selene_commands_with_wait__framework/framework/extensions/selene.py
1
1709
import logging from typing import Tuple, List from examples.log_all_selene_commands_with_wait__framework.framework.extensions.python.logging import ( TranslatingFormatter, ) def log_with( logger, *, added_handler_translations: List[Tuple[str, str]] = (), ): """ returns decorator factory with logging to specified logger with added list of translations to decorate Selene's waiting via config._wait_decorator. Example: from selene.support.shared import browser from framework.extensions.selene import log_with import logging logger = logging.getLogger('SE') browser.config._wait_decorator = log_with( logger, added_handler_translations = [ ('browser.element', 'element'), ('browser.all', 'all'), ] ) ... """ TranslatingFormatter.translations = added_handler_translations handler = logging.StreamHandler() formatter = TranslatingFormatter("[%(name)s] - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) def decorator_factory(wait): def decorator(for_): def decorated(fn): entity = wait.entity logger.info('step: %s > %s: STARTED', entity, fn) try: res = for_(fn) logger.info('step: %s > %s: ENDED', entity, fn) return res except Exception as error: logger.info('step: %s > %s: FAILED: %s', entity, fn, error) raise error return decorated return decorator return decorator_factory
mit
b1fbb4f7f44984e1ef00561748dc17bf
27.966102
103
0.577531
4.631436
false
false
false
false
yashaka/selene
tests/acceptance/helpers/givenpage.py
1
3147
# MIT License # # Copyright (c) 2015-2022 Iakiv Kramarenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os from tests.helpers import convert_sec_to_ms EMPTY_PAGE_URL = ( 'file://' + os.path.abspath(os.path.dirname(__file__)) + '/../../../resources/empty.html' ) class LoadingHtmlPage: def __init__(self, timeout=0, body=''): self._body = body self._timeout = timeout def load_in(self, driver): driver.get(EMPTY_PAGE_URL) return LoadedHtmlPage(driver).render_body(self._body, self._timeout) class LoadedHtmlPage: def __init__(self, driver): self._driver = driver def render_body(self, body, timeout=0): self._driver.execute_script( 'setTimeout(function() { document.getElementsByTagName("body")[0].innerHTML = "' + body.replace('\n', ' ').replace('"', '\\"') + '";}, ' + str(convert_sec_to_ms(timeout)) + ');' ) return self def execute_script(self, script): self._driver.execute_script(script) return self def execute_script_with_timeout(self, script, timeout): self._driver.execute_script( "setTimeout(function() { " + script.replace("\n", " ") + " }, " + str(convert_sec_to_ms(timeout)) + ");" ) return self def render_body_with_timeout(self, body, timeout): return self.render_body(body, timeout) class GivenPage: def __init__(self, driver): self._driver = driver def load_body_with_timeout(self, body, timeout): return LoadedHtmlPage(self._driver).render_body_with_timeout( body, timeout ) def opened_with_body_with_timeout(self, body, timeout): return LoadingHtmlPage(timeout, body).load_in(self._driver) def opened_with_body(self, body): return self.opened_with_body_with_timeout(body, 0) def opened_empty(self): return LoadingHtmlPage().load_in(self._driver) def load_body(self, body): return LoadedHtmlPage(self._driver).render_body(body)
mit
31a9c798d7339a373f825a44e355f2a8
32.478723
92
0.651414
3.953518
false
false
false
false
uclapi/uclapi
backend/uclapi/common/tests.py
1
17789
from django.test import TestCase, SimpleTestCase from .decorators import ( _check_general_token_issues, _check_oauth_token_issues, _check_temp_token_issues, _get_last_modified_header, how_many_seconds_until_midnight, get_var, throttle_api_call, UclApiIncorrectTokenTypeException ) from .helpers import ( generate_api_token, PrettyJsonResponse as JsonResponse, RateLimitHttpResponse as HttpResponse ) from dashboard.models import ( App, User ) from dashboard.app_helpers import get_temp_token, generate_temp_api_token from oauth.models import OAuthToken, OAuthScope from oauth.scoping import Scopes from freezegun import freeze_time from rest_framework.test import APIRequestFactory from uclapi.settings import REDIS_UCLAPI_HOST import datetime import json import redis import time class SecondsUntilMidnightTestCase(SimpleTestCase): def test_seconds_until_midnight(self): arg_list = [ "2017-05-29 23:59:59", "2017-05-29 00:00:00", "2017-05-29 00:00:01" ] expected = [ 1, 0, 86399 ] for idx, arg in enumerate(arg_list): with freeze_time(arg): self.assertEqual( how_many_seconds_until_midnight(), expected[idx] ) class HttpResponseTestCase(TestCase): def test_check_headers_set(self): headers = { 'Last-Modified': '1', 'X-RateLimit-Limit': '2', 'X-RateLimit-Remaining': '3', 'X-RateLimit-Retry-After': '4' } response = HttpResponse( "hello", custom_header_data=headers ) for key in headers: self.assertEqual(response[key], headers[key]) class GetVarTestCase(TestCase): test_factory = APIRequestFactory() def test_get_parameters(self): request = self.test_factory.get( '/test/test?parameter1=five&parameter2=20' ) p1 = get_var(request, "parameter1") p2 = get_var(request, "parameter2") self.assertEqual(p1, "five") self.assertEqual(p2, "20") def test_post_parameters(self): request = self.test_factory.post('/test/test', { "username": "testuser", "password": "apassword!$", "some_number": 123 }) p1 = get_var(request, "username") p2 = get_var(request, "password") p3 = get_var(request, "some_number") self.assertEqual(p1, "testuser") self.assertEqual(p2, "apassword!$") self.assertEqual(p3, "123") def test_get_and_post_parameters(self): request = self.test_factory.post( '/test/test?get_param_1=test_param', { "post_param_1": "testcase", "post_param_2": "some_other_param_case", "something_else": "$$$!!!___***" } ) p1 = get_var(request, "get_param_1") p2 = get_var(request, "post_param_1") p3 = get_var(request, "post_param_2") p4 = get_var(request, "something_else") self.assertEqual(p1, "test_param") self.assertEqual(p2, "testcase") self.assertEqual(p3, "some_other_param_case") self.assertEqual(p4, "$$$!!!___***") class ThrottleApiCallTest(TestCase): def test_throttling(self): token = generate_api_token("test") ( throttled, limit, remaining, reset_secs ) = throttle_api_call(token, "test-token") self.assertFalse(throttled) self.assertEqual(limit, 1) self.assertEqual(remaining, 0) # Not testing reset_secs as this is handled by testing # the how_many_seconds_until_midnight() function above ( throttled, limit, remaining, reset_secs ) = throttle_api_call(token, "test-token") self.assertTrue(throttled) self.assertEqual(limit, 1) self.assertEqual(remaining, 0) def test_throttle_bad_token_type(self): token = generate_api_token() with self.assertRaises(UclApiIncorrectTokenTypeException): ( throttled, limit, remaining, reset_secs ) = throttle_api_call(token, "incorrect") class TempTokenCheckerTest(TestCase): def setUp(self): self.valid_token = get_temp_token() def test_personal_data_requested(self): result = _check_temp_token_issues( self.valid_token, True, "/roombookings/bookings", None ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Personal data requires OAuth." ) def test_token_does_not_exist(self): invalid_token = "uclapi-temp-this-token-does-not-exist" result = _check_temp_token_issues( invalid_token, False, "/roombookings/bookings", None ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Temporary token is either invalid or expired." ) def test_invalid_path_requested(self): result = _check_temp_token_issues( self.valid_token, False, "/roombookings/some_other_path", None ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Temporary token can only be used for /bookings." ) def test_page_token_provided(self): result = _check_temp_token_issues( self.valid_token, False, "/roombookings/bookings", "abcdefgXYZ" ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Temporary token can only return one booking." ) def test_expired_token_provided(self): r = redis.Redis(host=REDIS_UCLAPI_HOST) expired_token = generate_temp_api_token() # We initialise a new temporary token and set it to 1 # as it is generated at its first usage. r.set(expired_token, 1, px=1) time.sleep(0.002) result = _check_temp_token_issues( expired_token, False, "/roombookings/bookings", None ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Temporary token is either invalid or expired." ) def test_all_passes(self): result = _check_temp_token_issues( self.valid_token, False, "/roombookings/bookings", None ) self.assertEqual( result, self.valid_token ) class GeneralTokenCheckerTest(TestCase): def setUp(self): self.valid_user = User.objects.create( email="testuserabc@ucl.ac.uk", full_name="Test User", given_name="Test", cn="test2", department="Dept. of Tests", employee_id="TESTU12345", raw_intranet_groups="test1;test2", agreement=True ) self.valid_app = App.objects.create( user=self.valid_user, name="Test App" ) def test_check_personal_data(self): result = _check_general_token_issues( self.valid_app.api_token, True ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Personal data requires OAuth." ) def test_check_nonexistent_token(self): result = _check_general_token_issues( "uclapi-blah-blah-blah", False ) self.assertTrue(isinstance(result, JsonResponse)) data = json.loads(result.content.decode()) self.assertEqual(result.status_code, 400) self.assertFalse(data['ok']) self.assertEqual( data['error'], "Token does not exist." ) def test_check_all_ok(self): result = _check_general_token_issues( self.valid_app.api_token, False ) self.assertEqual( result.api_token, self.valid_app.api_token ) class GenerateApiTokenTest(TestCase): def test_general_token_test(self): token = generate_api_token() self.assertEqual( len(token), 70 ) self.assertEqual( token[:7], "uclapi-" ) def test_temp_token_test(self): token = generate_api_token("temp") self.assertEqual( len(token), 75 ) self.assertEqual( token[:12], "uclapi-temp-" ) def test_user_token_test(self): token = generate_api_token("user") self.assertEqual( len(token), 75 ) self.assertEqual( token[:12], "uclapi-user-" ) class OAuthTokenCheckerTest(TestCase): def setUp(self): self.valid_user = User.objects.create( email="testuserabc@ucl.ac.uk", full_name="Test User", given_name="Test", cn="test2", department="Dept. of Tests", employee_id="TESTU12345", raw_intranet_groups="test1;test2", agreement=True ) self.valid_user.save() self.valid_app = App.objects.create( user=self.valid_user, name="Test App" ) self.valid_app.save() self.empty_scope = OAuthScope.objects.create( scope_number=0 ) self.empty_scope.save() s = Scopes() scope_num = s.add_scope(0, 'timetable') self.timetable_scope = OAuthScope.objects.create( scope_number=scope_num ) self.timetable_scope.save() self.valid_oauth_token = OAuthToken.objects.create( app=self.valid_app, user=self.valid_user, scope=self.empty_scope ) self.valid_oauth_token.save() def test_nonexistent_token(self): result = _check_oauth_token_issues( "uclapi-user-blah-blah-blah", "not-applicable", [] ) self.assertTrue(isinstance(result, JsonResponse)) self.assertEqual( result.status_code, 400 ) data = json.loads(result.content.decode()) self.assertFalse(data["ok"]) self.assertEqual( data["error"], "Token does not exist." ) def test_bad_client_secret(self): result = _check_oauth_token_issues( self.valid_oauth_token.token, "incorrect-client-secret", [] ) self.assertTrue(isinstance(result, JsonResponse)) self.assertEqual( result.status_code, 400 ) data = json.loads(result.content.decode()) self.assertFalse(data["ok"]) self.assertEqual( data["error"], "Client secret incorrect." ) def test_inactive_token(self): self.valid_oauth_token.active = False self.valid_oauth_token.save() result = _check_oauth_token_issues( self.valid_oauth_token.token, self.valid_app.client_secret, [] ) self.assertTrue(isinstance(result, JsonResponse)) self.assertEqual( result.status_code, 400 ) data = json.loads(result.content.decode()) self.assertFalse(data["ok"]) self.assertEqual( data["error"], "The token is inactive as the user has revoked " "your app's access to their data." ) def test_wrong_scope(self): self.valid_oauth_token.active = True self.valid_oauth_token.save() result = _check_oauth_token_issues( self.valid_oauth_token.token, self.valid_app.client_secret, ['timetable'] ) self.assertTrue(isinstance(result, JsonResponse)) self.assertEqual( result.status_code, 400 ) data = json.loads(result.content.decode()) self.assertFalse(data["ok"]) self.assertEqual( data["error"], "The token provided does not have " "permission to access this data." ) def test_valid_token(self): self.valid_oauth_token.scope = self.timetable_scope self.valid_oauth_token.save() result = _check_oauth_token_issues( self.valid_oauth_token.token, self.valid_app.client_secret, ['timetable'] ) self.assertEqual( result.token, self.valid_oauth_token.token ) def test_deleted_app_valid_token(self): self.valid_oauth_token.active = True self.valid_oauth_token.save() self.valid_app.deleted = True self.valid_app.save() result = _check_oauth_token_issues( self.valid_oauth_token.token, self.valid_app.client_secret, ['timetable'] ) self.assertTrue(isinstance(result, JsonResponse)) self.assertEqual( result.status_code, 403 ) data = json.loads(result.content.decode()) self.assertFalse(data["ok"]) self.assertEqual( data["error"], "The token is invalid as the developer has " "deleted their app." ) class LastModifiedHeaderTestCase(TestCase): base_redis_key = "http:headers:Last-Modified:" def test_redis_case_1(self): redis_key = self.base_redis_key + __name__ r = redis.Redis(host=REDIS_UCLAPI_HOST) r.set( redis_key, "2019-01-24T00:10:05+01:00" ) last_modified_header = _get_last_modified_header(__name__) self.assertEqual( last_modified_header, "Wed, 23 Jan 2019 23:10:05 GMT" ) r.delete(redis_key) def test_redis_case_2(self): redis_key = self.base_redis_key + __name__ r = redis.Redis(host=REDIS_UCLAPI_HOST) r.set( redis_key, "2019-01-24T00:10:05+00:00" ) last_modified_header = _get_last_modified_header(__name__) self.assertEqual( last_modified_header, "Thu, 24 Jan 2019 00:10:05 GMT" ) r.delete(redis_key) def test_redis_case_3(self): redis_key = self.base_redis_key + __name__ r = redis.Redis(host=REDIS_UCLAPI_HOST) r.set( redis_key, "2018-12-25T00:13:02-05:00" ) last_modified_header = _get_last_modified_header(__name__) self.assertEqual( last_modified_header, "Tue, 25 Dec 2018 05:13:02 GMT" ) r.delete(redis_key) def test_current_time_case_1(self): last_modified_header = _get_last_modified_header() current_time = datetime.datetime.utcnow() last_modified_timestamp = datetime.datetime.strptime( last_modified_header, "%a, %d %b %Y %H:%M:%S GMT" ) # We can't just assert that the timestamps will be exactly equal # as we can't guarantee that the testcase will all run within # one single second. # Thank you, Stack Overflow! # https://stackoverflow.com/a/4695663 margin = datetime.timedelta(seconds=3) self.assertTrue( ( last_modified_timestamp - margin <= current_time <= last_modified_timestamp + margin ) ) def test_redis_nonexistent_1(self): last_modified_header = _get_last_modified_header( "NONEXISTENTDONOTUSEABCXYZ" ) current_time = datetime.datetime.utcnow() last_modified_timestamp = datetime.datetime.strptime( last_modified_header, "%a, %d %b %Y %H:%M:%S GMT" ) # We use the same assertions as the one for the current timestamp # as the key won't return any results. margin = datetime.timedelta(seconds=3) self.assertTrue( ( last_modified_timestamp - margin <= current_time <= last_modified_timestamp + margin ) )
mit
fa6c7f0c1beeba0b7d208b8c4f2b9a06
27.831442
73
0.545449
4.054011
false
true
false
false