index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
27,816,949
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/subdemo/test_demo1.py
|
import pytest
@pytest.fixture()
def connectDB():
print("test_demo1 下的 conftest")
def test_a(connectDB):
print("这是sub_demo中test_a")
class TestB:
def test_b(self):
print("这是sub_demo中test_b")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,950
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/os_1.py
|
import inspect
import os
def be_call_fun():
# stack()返回的是调用栈列表。
frame_stack = inspect.stack()
# 0是标识当前函数的栈,1是标识上一层函数的栈,依此类推。
# 也就是这个数值不一定是1,要看你要获取其文件路径的函数在第几层
caller_frame = frame_stack[1]
caller_file_path = caller_frame.filename
# 由于当前调用函数和被调用函数放在同一个文件,所以文件名还是当前文件名
# 可将调用函数和被调用函数放到不同文件进行观察
print(f"caller_file_path: {caller_file_path}")
def caller_fun():
be_call_fun()
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
print(os.path.abspath(os.path.dirname(os.getcwd())))
print(os.path.abspath(os.path.join(os.getcwd(), "..")))
print(os.path.dirname(os.getcwd()))
if __name__ == "__main__":
caller_fun()
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,951
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func2_test.py
|
"""
列表的特性
list.append(x):在列表的末尾添加一个元素,相当于a[len(a)] = [x]
list.insert(i,x):在给定的位置插入一个元素,第一个参数是要插入的元素的索引,以a.insert(0,x)插入列表头部,a.insert(len(a),x)等同于a.append(x)
list.remove(x):移除列表中第一个值为x的元素,如果没有这样的元素,则抛出ValueError异常
list.pop([i]):删除列表中给定位置的元素并返回她,如果没有给定位置,a.pop()将会删除并返回列表中的最后一个元素
list.sort(key=None,reverse=False):对列表中的元素进行排序(参数可用于自定义排序,解释请参见sorted()
list.reverse():反转列表中的元素
"""
# list_test = [3,4,5]
# list_test.append(1)
# list_test.insert(1,2)
# list_test.remove(1)
# y = list_test.pop()
# print(y)
# list_test.sort()
# list_test.sort(reverse=True)
# list_test.reverse()
# print (list_test)
"""
list.clear():删除列表中所有的元素,相当于del a[:]
list.extend(iterable):使用可以迭代对象中的所有元素来扩展列表,相当于a[len(a):] = iterable
list.index(x[,start[,end]]):返回列表中第一个值为x的元素的从零开始的索引。如果没有这样的元素将会抛出ValueError异常
可选参数start和end是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是start参数
list.count(x):返回元素x在列表中出现的次数
list.copy():返回列表的一个浅拷贝,相当于a[:]
注意:
insert、remove或者 sort方法,只修改列表,没有打印处返回值---他们返回默认值None 这是python中所有可变数据结构的设计原则
并非所有的数据或可排序或比较(字符串和数字等)
"""
"""
列表推导式:
概念:列表推导式提供了一哥更简单的创建列表的方法。常见的用法是把某种操作应用于序列或可迭代对象的每个元素上,然后使用其结果来创建列表,或者通过满足某些特定条件元素来创建子序列
练习题:
如果我们想生成一个平方列表,比如[1,4,9.....],使用for循环怎么写? 使用列表推导式又怎么写?
"""
#使用for循环创建平方列表
list_square = []
for i in range(1,4):
list_square.append(i**2)
print("list_square", list_square)
#使用列表推导式生成列表,本质还是执行一个for循环
list_square2 = [i**2 for i in range(1,4)]
print("list_square2" ,list_square2)
#加入条件判断
list_square3 = []
for i in range(1,4):
if i!=1:
list_square3.append(i**2)
print("list_square3", list_square3)
list_square6 = [i**2 for i in range(1,4) if i != 1]
print("list_square6", list_square6)
list_square4 = [i*j for i in range(1,4) for j in range(1,4)]
print ("list_square4", list_square4)
list_square5 = []
for i in range(1,4):
for j in range(1,4):
list_square5.append(i*j)
print("list_squares", list_square5)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,952
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/pytest_info_test.py
|
"""
pytest测试框架
测试用例的识别和运行
测试文件:
--test_*.py
--*_test.py
用例识别:
--Test*类包含的所有test_*的方法(重点:测试类中不能带有__init__方法)
--不在class中的所有test_*方法
pytest也可以执行unittest框架写的测试用例和方法
"""
import pytest
def func(x):
return x + 1
#参数化,重点需要掌握内容
@pytest.mark.parametrize('a,b', [
(1,2),
(10,20),
('a1', 'a2'),
(3,4),
(5,6)
])
def test_answer(a, b):
assert func(a) == b
def test_answer1():
assert func(4) == 5
"""
fixture使用详解:
1、fixture可以当做参数传入
定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture(),fixture命名不要以test开头,跟用例区分开。
fixture是有返回值得,没有返回值默认为None。用例调用fixture的返回值,直接就是把fixture的函数名称当做变量名称。
示例:
@pytest.fixture()
def test_01():
a = 5
return a
def test_02(test_01):
assert test_01 == 5
print("断言成功")
2、使用多个fixture
如果用例需要用到多个fixture的返回数据,fixture也可以返回一个元祖,list或字典,然后从里面取出对应数据。
示例:
@pytest.fixture()
def test_01():
a = 5
b = 6
return (a, b)
def test_02(test_01):
a = test_01[0]
b = test_01[1]
assert a < b
print("断言成功")
3、fixture的作用范围(scope)
fixture里面有个scope参数可以控制fixture的作用范围:session>module>class>function
-function:每一个函数或方法都会调用
-class:每一个类调用一次,一个类中可以有多个方法
-module:每一个.py文件调用一次,该文件内又有多个function和class
-session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
示例:
@pytest.fixture(scope="class")
def test_01():
a = 5
b = 6
return (a, b)
class TestNum:
def test_02(self,test_01):
a = test_01[0]
b = test_01[1]
assert a < b
print("断言成功")
"""
@pytest.fixture()
def login():
username = 'Lily'
print("登陆结果")
return username
class TestDemo:
#
def test_a(self,login):
print(f"a username = {login}")
def test_b(self):
print("b")
def test_c(self,login):
print(f"c username = {login}")
#python解释器运营入口方法
if __name__ == '__main__':
#实际上是使用pytest解释器执行
pytest.main(['pytest_info_test.py']) #使用pytest解释器执行全部测试用例 pytets + .py文件
#pytest.main(['pytest_info_test.py::TestDemo','-v']) #使用python解释器,模仿pytest解释器中的模式 python + .py文件 指定某条测试用例或者某个测试类来执行
#pytest.main(['pytest_info_test.py','-v'])#python + .py文件
"""
pytest命令参数:
-k: 指定某条测试用例执行 pytest -k + 指定的测试用例的名称
-m:
"""
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,953
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_decrypt_1.py
|
from interface_test_framework.testcases import test_decrypt
import pytest
class TestApiRequest:
req_data = {
"method": "get",
"url": "http://127.0.0.1:10000/demo64.txt",
"headers": None,
"encoding": "base64"
}
def test_send(self):
#实例化
ar = test_decrypt.ApiRequest()
print(ar.send(self.req_data))
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,954
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func6_test.py
|
"""
文件的读取
读写文件的操作步骤:
1、打开文件,获取文件描述符
2、操作文件描述符(读 |写)
3、关闭文件
使用方法:
open(file,mode='r',buffering=-1.encoding=None,errors=None,newline=None,closefd=True,opener=None)
参数说明:
name:文件名称
mode:只读r、写入w、追加a,默认文件访问模式为r;x创建一个文件并编写它 +:磁盘更新(读+写)
buffering:寄存区缓存
0-不寄存
1-访问文件时会寄存行
>1-寄存区的缓冲大小
负值-寄存区的缓冲大小则为系统默认
注意:文件读写操作完成后,应该及时关闭文件
"""
f = open("data.txt")
print(f.readable())
#读取全部行
#print(f.readlines())
#读取一行
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
#with语句块可以将文件打开后操作完毕后自动关闭这个文件
#图片读取需要使用rb,读取二进制的格式
#正常的文本,可以使用rt,也就是默认格式即可
with open("data.txt") as f:
while True:
line = f.readline()
if line:
print(line)
else:
break
#print(f.readlines())
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,955
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/exercises.py
|
"""
练习题 1、计算1~100求和
2、加入分支结构实现1~100之间的偶数求和
3、使用python实现1~100之间的偶数求和
"""
#练习题1
#import random
import random
result = 0
for i in range(101):
print(i)
result = result + i
print(result)
#练习题2
result = 0
for i in range(101):
if(i%2 == 0):
print(i)
result = result + i
print(result)
#练习题3
result = 0
for i in range(2, 101, 2):
print(i)
result = result + i
print(result)
"""
猜数字游戏
1、计算机出一个1~100之间的随机数由人来猜
2、计算机根据人猜的数字分别
3、给出提示大一点/小一点/猜对了
"""
#随机出一个1~100的数字
computer_number = random.randint(0,100)
print(computer_number)
while True:
person_number = int(input("请输入一个数字"))
if person_number > computer_number:
print("小一点")
elif person_number < computer_number:
print("大一点")
else:
print("猜对了")
break
#猜数字游戏封装版
def game_Number(computer_number):
while True:
person_number = int(input("请输入一个数字"))
if computer_number < person_number:
print("小一点")
elif computer_number > person_number:
print("大一点")
else:
print("猜对了")
break
computer_number = random.randint(0, 100)
game_Number(computer_number)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,956
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_form_request.py
|
"""
结构化请求体构造JSON XML
JSON请求体构造
payload={‘some’:‘data’}
r = request.post(url,json=payload)
XML请求体构造
复杂数据解析 mustache
schema校验
https://jsonschema.net/
生成schema文件
根据需要添加自定义规则
"""
import requests
class TestDemo:
def test_post_json(self):
payload = {'some': 'data'}
r = requests.post('https://httpbin.testing-studio.com/post', json=payload)
print(r.text)
print(r.json())
print(r.status_code)
assert r.status_code == 200
assert r.json()['json']['some'] == "data"
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,957
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/python_combat/src/pyrhon-combat.py
|
"""
python脚本编写
相关链接:https://docs.python.org/3/
pip源切换
https://mirrors.aliyun.com/pypi/simple/------阿里云
https://pypi.tuna.tsinghua.edu.cn/simple----清华
http://pypi.douban.com/simple/--------豆瓣
依赖清单:pip list
pip freeze
pip freeze > requirements.txt--输出本地包环境至文件
pip install -r requirements.txt---根据文件进行包安装
github/ceshiren
在github中创建自己得仓
往自己的仓库中添加代码?
1、本地创建git和远程创建关联
2、本地创建git会用到的主命令:
echo "# python_test_forme" >> README.md
git init--把本地目录变成版本管理工具
git add README.md--把文件添加进去
git commit -m "first commit"---修改提交
git branch -M main--创建分支
git remote add origin git@github.com:wangjinjin123/python_test_forme.git---创建关联pwd
git push -u origin main
查看已提交的代码:
git remote add origin git@github.com:wangjinjin123/python_test_forme.git
git branch -M main
git push -u origin main
ssh -T git@github.com---测试连接
私下学习了解更多的git命令
"""
"""
创建目录
创建包
api 源代码
tests 测试用例
"""
"""
实例变量和类变量搞清楚
"""
"""
数据结构和算法
刷题 + 多看成熟框架得源代码
如何刷题:
-leetcode 哪些题目?
--数据类型与算法:
列表(排序)、队列
链表(单链表 --逆序、插入)
栈(通常和链表结合考察,结合其他结构)
二(多)叉树(遍历、查找)(占比较重)(思维导图和测试用例转换)
"""
"""
工程师等级
1、简单的api、json、 yaml、 file、 re
2、面向对象
3、数据结构和算法---单兵作战能力,小范围作战 例如:思维导图生成测试用例
4、设计模式--多人协作、大范围的项目
"""
"""
预习:
--python 文档过一遍
--pytest官方文档过一遍
--看框架源代码
"""
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,958
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/unittest_info.py
|
"""
unnitest测试框架
--单元测试覆盖类型:
--语句覆盖
--条件覆盖
--判断覆盖
--路径覆盖
--框架介绍
--编写规范
--测试模块首先import unittest
--测试类必须继承 unittest.TestCase
--测试方法必须以“test_”
"""
import unittest
#定义测试类并继承unittest测试类
class TestStringMethods(unittest.TestCase):
#setUp 和 tearDown 方法是在每条测试用例的前后分别进行调用的方法
def setUp(self) -> None:#默认返回值是None
print("setup")
def tearDown(self) -> None:
print("teardown")
# setUpCalss 和 tearDownClass 方法是在整个类的前后分别调用的方法
#类级别的方法需要加一个装饰器:@classmethod
@classmethod
def setUpClass(cls) -> None:
print('set up class')
@classmethod
def tearDownClass(cls) -> None:
print('tear down class')
def test_play(self):
print('test abc')
def test_upper(self):
print('test_upper')
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
print('test_isupper')
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
print('test_split')
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
#环境准备的测试方法 不应该写在测试用例中
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,959
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/requests_method.py
|
import requests
#将get和post方法封装成request方法
class HttpRequest:
def request(self,url,method,**kwargs):#
if method.lower() == 'get':
res = requests.get(url,**kwargs)
else:
res = requests.post(url,**kwargs)
return res
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,960
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func8_test.py
|
"""
python的错误与异常
语法错误与定位
异常捕获、异常处理
自定义异常
"""
"""
异常既是一个事件
"""
try:
num1 = int(input("请输入一个被除数"))
num2 = int(input("请输入一个除数"))
print(num1/num2)
except:
print("程序出现异常了")
# except ZeroDivisionError:
# print("除数不能为0噢")
# except ValueError:
# print("只能输入数值型的整数")
# else:
# print("没有异常噢~很棒!")
finally:
print("这个流程已经走完了噢")
#手动抛出的异常
# a = 5
# if a < 10:
# raise Exception("这是一个手动抛出的异常")
#自定义异常
class MyException(Exception):
def __int__(self,value1,value2):
self.value1 = value1
self.value2 = value2
raise MyException("value1", "value2")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,961
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func9_test.py
|
"""
python面向对象编程
什么是面向对象:
类、方法、类变量的定义
实例引用、实例变量使用
面向对象开发就是不断的创建对象、使用对象、操作对象做事情
不同的人负责不同的模块并最后组装在一起
面向对象解释:
语言层面:封装代码和数据
规格层面:对象是一系列可被使用的公共接口
从概念层面:对象是某种拥有责任的抽象
程序设计规则:
1、有哪些类
2、每个类多有哪些属性和行为
3、类与类之间存在的关系
类:抽象的概念 一类事物
方法:类中定义的函数,对外提供的服务
类变量:类变量在整个实例化的对象中是公用的
实例引用:实例化一个对象 对象?
实例变量:以self.变量名的方式定义的变量
"""
#创建一个人类
#通过关键字class定义了一个类
class Person:
#类变量
name = "default"
age = 0
gender = "male"
weight = 0
#构造方法,在类实例化的时候被调用
def __init__(self, name, age, gender, weight):
#self。变量名的方式,访问到的是实例的变量
self.name = name
self.age = age
self.gender = gender
self.weight = weight
@classmethod #增加装饰器使其变成类方法以使类可以直接访问调用
def eat(self):
print(self.name,"eating")
def play(self):
print(self.name,"playing")
def jump(self):
print("jumping")
# def set_name(self, name):
# #self.name 调用类中的name属性
# self.name = name
# def set_age(self, age):
# self.age = age
#实例化类
xm = Person("小明", 18, "男", 90) #调用init方法
# zs.set_name("zhangsan")
# zs.set_age(20)
name_xm = xm.name
age_xm = xm.age
gender_xm = xm.gender
weight_xm = xm.weight
xm.eat()
xm.play()
print("zhangsan的名字是:",name_xm, "年龄是:" ,age_xm, "性别是 ",gender_xm, "体重是 ", weight_xm)
#类变量和和实例变量的区别,
#类变量和实例变量都是可以修改的
#类变量是需要类来访问的,实例变量需要实例来访问
#类方法需要添加一个修饰器 @classmethod
print(Person.name)
Person.name = "game"
print(Person.name)
print(xm.name)
xm.name = "李丽"
print(xm.name)
#类方法是实例方法
#类方法不能访问实例方法
Person.eat()
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,962
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func10_test.py
|
"""
python常用的标准库
操作系统相关:os
时间和日期相关:time datetime
科学技术相关:math
网路请求:urllib
"""
import os
import time
import urllib.request
import math
# # os.makedirs("testdir")
# print(os.listdir("./"))
# #os.removedirs("testdir")
# #获取当前路径
# print(os.getcwd())
#
#在文件夹b中创建一个test.txt文件
print(os.path.exists("b"))
if not os.path.exists("b"):
os.makedirs("b")
if not os.path.exists("b/test.txt"):
f = open("b/test.txt", "w")
f.write("hello,os using")
f.close()
# g = open("b/test.txt","w")
# g.write("wahaha"/n)
# g.close()
"""
获取当前时间以及时间格式经的模块
导入方式:import time
time模块常用的方法
1、time.asctime() 国外的时间格式
2、time.time() 时间戳
3、time.sleep() 等待
4、time.localtime() 时间戳转换成时间元组
5、 time.strftime() 将当前的时间戳转成带格式的时间
格式:time.strftime("%Y-%m-%d %H-%M-%S",time.localtime())
"""
# print(time.asctime())
# print(time.time())
# print(time.localtime())
# print(time.strftime("%Y-%m-%d %H: %M: %S", time.localtime()))
# print(time.strftime("%Y-%m-%d %H: %M: %S"))
#获取2天前现在的时间
# now_timestamp = time.time()
# two_day_before = now_timestamp - 60*60*24*2
# time_tumple = time.localtime(two_day_before)
# print(time.strftime("%Y-%m-%d %H: %M: %S", time_tumple))
"""
urllib库
python------import urllib2
response=urllib2.urlopen("url地址")
python------import urllib。request
response=urllib.request.urlopen("url地址")
"""
# response=urllib.request.urlopen("http://www.baidu.com")
# print(response.status)
# print(response.read())
# print(response.headers)
"""
math库
math.ceil(x) 返回大于等于参数x的最小整数
math.floor(x) 返回小于等于参数x的最大整数
math.sqrt(x) 平方根
"""
print(math.ceil(5.5))
print(math.floor(5.5))
print(math.sqrt(9))
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,963
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_fixture.py
|
import pytest
#fixture是pytest的一个外壳函数,可以模拟setup和teardown的操作
#yield之前的操作相当于setup,yiel之后的操作相当于teardown
#yield相当于 return,如果需要返回数据,直接放在yield后边
#创建一个登陆的fixture方法
#加上aotouse参数后,默认所有测试用例都调用,如果想要yield有返回值必须在函数中带fixture函数名
@pytest.fixture()
def login():
print("登陆操作")
print("获取token")
username= "tom"
password = "11111"
token = "token123"
#fixture中类似teardown的方式、
#使用yield返回数据
yield [username,password,token]
print("登出操作")
#测试用例1:需要提前登陆
def test_case1(login):
#想要使用fixture函数中返回的值,则直接在方法中使用fixture方法的名称即可
print(f"login username and password:{login}")
print("测试用例1")
#测试用例2:不需要提前登陆
def test_case2(connectDB):
print("测试用例2")
#测试用例3:需要提前登陆
def test_case3():
print("测试用例3")
#测试用例4:需要提前登陆
# @pytest.mark.usefixtures("login")
def test_case4():
print("测试用例4")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,964
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func1_test.py
|
"""
默认参数
默认参数在定义函数的时候使用k=v的形式定义
调用函数时,如果没有传递参数,则会使用默认参数;如果传入了参数则使用传入参数
"""
def func1(a=1):
print("参数a的值为", a)
func1()
"""
关键字参数
在调用函数的时候,使用k=v的方式进行传参
在函数调用/定义中,关键字参数必须跟随再位置参数的后边
"""
def func1_1(m, n, k, l):
print("参数m的值为", m)
print("参数n的值为", n)
print("参数k的值为", k)
print("参数l的值为", l)
func1_1(m = 1, l = 2, k = 4, n= 0)
"""
Lambda表达式
可以用lambda关键字来创建一个小的匿名函数
lambda的主体是一个表达式,而不是一个代码块,仅仅能在lambda表达式中封装有限的逻辑进去
"""
func1_2 = lambda x : x*2
print(func1_2(3))
#等价于以下函数
def func1_3(x):
return x*2
print(func1_3(3))
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,965
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/testcases/test_address_1.py
|
import pytest
from interface_test_combat.api.address_model import Address
class TestAddress:
def setup(self):
self.address = Address()
@pytest.mark.parametrize("userid, mobile",[('wang1','13728814500'),('wang2','13728814501'),('wang3','13728814502')])
def test_add_user(self,userid,mobile):
name = "星期四"
department = [1]
print(userid)
print(mobile)
#数据清理
self.address.dele_user(userid)
#创建成员
r = self.address.add_user(userid,name,mobile,department)
print(r)
assert r.get("errcode") == 0
#查询成员确认创建成功
r = self.address .get_user(userid)
#print(r)
#此处使用python字典的get方法获取字典中的value
assert r.get("name", "userid 添加失败") == name
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,966
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/demo1.py
|
# from baidu import search, SearchDemo
# from baidu import hello
from baidu import*
#import baidu
search()
#baidu.search()
print(hello)
SearchDemo
"""
模块中常用的方法
dir() 找出当前模块定义的对象
dir(sys) 找出参数模块定义的对象的
"""
print(dir())
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,967
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/test_allure_basicreport.py
|
"""
使用allure生成测试报告
1、安装allure-pytest插件
pip install allure-pytest
2、运行
在测试执行期间搜集结果
pytest [测试文件] -s -q --alluredir=./result/(--alluredir这个选项用于指定存储测试结果的路径)
查看测试报告
方式一、测试完成后查看实时报告,在线看报告,会直接打开默认浏览器展示当前报告
allure serve ./result/(注意:这里的serve得书写)
方式二、从结果生成报告,这是一个启动tomacat得读物,需要两个步骤:生成报告、打开报告
生成报告:
allure generate ./result/ -o ./report/ --clean(注意:覆盖路径加--clean)
打开报告:
allure open -h 127.0.0.1 -p 8883 ./report/
执行测试用例并把测试结果指定至某个路径下
$pytest --alluredir=/tmp/my_allure_results
生成测试报告(html)。线上实时查看
$ allure serve /tmp/my_allure_results
"""
import pytest
def test_success():
"""this test succeeds"""
assert True
def test_failure():
"""this test fails"""
assert False
def test_skip():
"""this test is skipped"""
pytest.skip('for a reason!')
def test_broken():
raise Exception('oops')
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,968
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/path_data.py
|
# import datetime
# import os
# import time
#
#
# path_1 = os.path.realpath(__file__)
# print(path_1)
# path_2 = os.path.dirname(os.path.realpath(__file__))
# print(path_2)
# BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# print(BASE_PATH)
#
# print(datetime.date.today())
# log_name = "logs"
#
# a = log_name + "_" + str(datetime.date.today()) + ".log"
# b = os.path.join(BASE_PATH, "logs", a)
# print(a)
# print(b)
import requests
from interface_test_combat.api.address_model import Address
url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwec359d0349cb57a1&corpsecret=JzhIasSlUFfz81kPlM-m1-qwSbG2JH4hQiZ1r6_2TqQ"
r = requests.get(url)
token = r.json()['access_token']
print(token)
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={token}"
body = {
"userid": "today",
"name": "今天",
#"alias": "Judy",
"mobile": "13728814590",
"department": [1]
}
r = requests.post(url, json=body)
print(r.json())
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,969
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/test_demo.py
|
import json
import requests
#获取通讯录得token
def test_demo():
url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwec359d0349cb57a1&corpsecret=JzhIasSlUFfz81kPlM-m1-qwSbG2JH4hQiZ1r6_2TqQ"
r = requests.get(url)
token = r.json()["access_token"]
#读取成员
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={token}&userid=WangJinJin"
r = requests.get(url)
# print(r.json())
# print(r.json()["errcode"])
#修改成员信息
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={token}"
body = {
"userid": "WangJinJin",
"name": "云沐"
}
header = {'content-type' : "application/json"}
r = requests.post(url, data=json.dumps(body), headers = header)
print(r.json())
#添加成员
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={token}"
body1 = {
"userid": "moyuqingfeng",
"name": "墨雨清风",
"alias": "Judy",
"mobile": "13728814530",
"department": [1]
}
body2 = {
"userid": "xiaobai",
"name": "小白只蠢不萌",
"alias": "Lily",
"mobile": "13728814535",
"department": [1]
}
body3 = {
"userid": "ceshishanchu",
"name": "删除",
"alias": "Lucy",
"mobile": "13728814525",
"department": [1]
}
r1 = requests.post(url, json=body1)
r2 = requests.post(url, json=body2)
r3 = requests.post(url, json=body3)
# print(r1.json())
# print(r2.json())
#删除成员
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={token}&userid=ceshishanchu"
r = requests.get(url)
#print(r.json())
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,970
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func4_test.py
|
"""
python的模块学习
项目的目录结构
模块的定义
文件的引用
"""
"""
项目目录结构
python的程序结构:project项目----package包-----module模块----function方法
模块:
包含Python定义和语句的文件
.py文件
作为脚本运行
模块导入:
import 模块名
from 模块名 import 方法 | 变量 | 类
from 模块名 import*
注意:
同一个模块写多次,只被导入一次
import应该放在代码的顶端
模块分类:
系统内置模块
第三方的开源模块
自定义模块
系统内置模块:
python安装好后自带的 例如:sys os time json等
第三方的开源模块:
通过pip可自行安装
"""
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,971
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_param.py
|
import pytest
import yaml
#封装需要用到的数据
def get_datas():
with open("D:\pycharm\pythonproject\pytest_combat\data\data.yaml") as f:
datas = yaml.safe_load(f)
print(datas)
add_datas = datas["datas"]
add_ids = datas["myids"]
return [add_datas,add_ids]
def add_func(a,b):
return a+b
@pytest.mark.parametrize("a,b,expected",get_datas()[0],ids= get_datas()[1])
def test_add(a,b,expected):
print(a)
print(b)
assert add_func(a,b) == expected
#参数可以组合堆叠使用
@pytest.mark.parametrize(("a"),[1,2,3],ids=["a","b","c"])
@pytest.mark.parametrize(("b"),[1,2,3],ids=["a1","b1","c1"])
def test_foo(a,b):
print("测试参数堆叠组合:a->%s,b->%s" %(a,b))
print(f"测试参数堆叠组合:{a},{b}")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,972
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/parame_pytest.py
|
"""
使用参数化功能管理类似用例
1、数据写死在py中
@pytest.mark.parametrize(argnames, argvalues)
--argnames: 要参数化的变量, 可以是:string (逗号分隔)、list、tuple
--argvalues: 参数化的值,list、list[tuple]
argnames和argvalues一定是一一对应的
2、数据存在yaml文件中
list:
- 10
- 20
- 30
dict:
by:id
locator:name
action:click
进行嵌套:
-
- by:id
- locator:name
- action:click
companies:
-
id:1
name:company1
price:200w
-
id:2
name:company2
price:500w
"""
import pytest
#使用sring
@pytest.mark.parametrize("a,b",[(10,20),(20,30)])
def test_param(a,b):
print(a+b)
#使用list
@pytest.mark.parametrize(['a','b'],[(10,20),(20,30)])
def test_param(a,b):
print(a+b)
assert a+b == 50
#使用tuple
@pytest.mark.parametrize(('a','b'),[(10,20),(20,30)])
def test_param(a,b):
print(a+b)
assert a+b == 30
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,973
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/test_allure_attach.py
|
"""
前端自动化测试-截图
场景:
前端自动化测试经常需要附加图片或者html,在适当得地方,适当得时机截图
解决:
@allure.attach显示许多不同类型得提供得附件,可以补充测试、步骤或者测试结果
步骤:
---在测试报告中附加网页:
allure.attach(body(内容),name,attachment_type,extension)
allure.attach('<head></head><body>首页</body>‘,“这是错误的信息”,allure.attachment_type.HTML)
----在测试报告中附加图片
allure.attach.file(source,name,attachment_type,extension)
allure.attach.file(./resource/222.jpg,attachment_type=allure.attachment_type.JPG)
"""
import allure
def test_attach_text():
attach
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,974
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func5_test.py
|
"""
python输入和输出
字面量打印和格式化
文件读取
Json格式转换
"""
"""
字面量(literal)是以变量或常量给出的原始数据。在程序中可以直接使用字面量
字面量的类型:
数值型
字符型
布尔型
字面量集合:列表 集合 元组 字典
特殊字面量:None
"""
"""
字面量插值
字面量插值就是将变量、常量以及表达式插入的一种技术,它可以避免字符串拼接的问题,很多余元都支持了此功能
字面量插值方法:
1、格式化输出
2、通过string.format()方法拼接
Formatted string literals,字符串格式化机制(>python 3.6)
"""
"""
格式化输出
%的用法
%s :使用str()函数将表达式转换为字符串
%d、%i :转化为带符号的十进制整数
%f /%F:转化为十进制浮点数
"""
age = 3
name = "Lucy"
print('%s,my age is %d' %(name,age))
print('%s,my age is %d, my number is %f' %(name,age,3.1415926))
print('%s,my age is %d, my number is %f' %(name,age,3.14159))
print('%s,my age is %d, my number is %.3f' %(name,age,3.14159))
"""
format()方法
用法:str.format()可将
字符串 print("we are the {} and {} ".format('Tom', 'Jerry'))
列表 print("we are the {0} and {1}".format(*listdata))
字典 print("my name is {name},age is {age}".format(**dictdata))
"""
name1 = 'Lily'
age1 = 20
print('my name is {}, age is {}'.format(name1, age1))
print('my name is {0}, age is {1} ,{0}{1}'.format(name1, age1))
list = ["a",2,3,4]
dict = {"name": "jim", "gender": "male"}
print("my list is {0}, dict is {1}".format(list, dict))
namelist = ["hali", "jerry", "alex"]
#加*相当于给列表解包,拆分成3个
print("we name is : {} 、 {} and {}".format(*namelist))
print("my name is {name}, gender is {gender}".format(**dict))
"""
F-strings:字符串格式化机制 python 3.6以上
使用方法:f'{变量名},'
注意:
大括号里面可以是表达式或者函数
大括号内不能转义,不能使用‘\’
"""
print(f"my name is {name1}, age is {age1}")
print(f"my name is {name1.upper()}, age is {age1}")
print(f"result is {(lambda x:x+1)(2)}")
print(f"result is {11}")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,975
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func3_test.py
|
#元组(tuple)使用()进行定义
#tuple、list、range都是序列数据类型
#元组是不可变的,可以通过解包、索引来访问
#元组的定义
from typing import Set, Any
# tuple_1 = (1,2,3)
# tuple_2 = 1,2,3
# print("tuple_1",tuple_1)
# print("tuple_2",tuple_2)
# print(type(tuple_1))
# print(type(tuple_2))
#
#
# #元组的不可变特性
# list_1 = [1,2,3]
# list_1[1] = 0
# print(list_1)
#
# #执行报错,元组不可变
# # tuple_3 = (1,2,3,4)
# # tuple_3[0] = 0
#
# a = [1,2,3]
# tuple_4 = (4,5,a)
# #打印元组中的指针地址
# print(id(tuple_4[2]))
#
# tuple_4[2][1] = 0
# print("tuple_4",tuple_4)
# print(id(tuple_4[2]))
#元组内置函数
# a = (1,2,3,1)
# print(a.count(1))
# #多个相同的元素则返回首个的角标值
# print(a.index(1))
"""
集合是由不重复元素组成的无序的集合
它的基本用法包括成员检测和消除重复元素
可以使用{}或者set()函数创建集合
要创建一个空集合只能使用set()而不能用{}
"""
# b = set()
# a1 = {1}
# print(len(b))
# print(type(a1))
# print(type(b))
# set_1 = {1, 2, 3}
# set_2 = {3, 4, 5}
# print(set_1)
#求集合的并集
#print(set_1.union(set_2))
#求集合的交集
#print(set_1.intersection(set_2))
#求集合的差集
#print(set_1.difference(set_2))
#添加集合元素
# set_1.add(8)
# print(set_1)
#使用列表推导式创建集合
# set_3 = {i for i in "seaaaeiriehfi"}
# print("set_3",set_3)
#
# #去重
# c = "aabbbeusieut"
# set_4 = set(c)
# print(set_4)
"""
字典是以【关键字】为索引
关键字可以是任意不可变类型,通常是字符串和数字如果一个元组只包含字符串、数字、或元组,那么这个元组也可用作关键字
"""
dict_1 = {}
dict_2 = dict(a=1, b=2)
dict_3 = {"a":1, "b":3, "c":5}
print(dict_1)
print(dict_2)
print(dict_3)
print(type(dict_1))
print(type(dict_2))
#字典的方法
#dict_2.pop("a")
print(dict_2.keys())
print(dict_2.values())
#删除一个key-value对并输出value
# print(dict_2.pop("a"))
# print(dict_2)
#随机删除一个键值对并返回
print(dict_3.popitem())
print(dict_3)
dict_1_1 = dict_1.fromkeys([1,2,3], "a")
print(dict_1_1)
#使用推导式创建字典
dict_4 = {i for i in range(1,4)}
print(dict_4)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,976
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/run.py
|
import unittest
from pytest_base.utill.HTMLTestRunner_PY3 import HTMLTestRunner
if __name__ == '__main__':
report_title = 'TestSearch用例执行报告'
desc = '我的第一个测试报告'
report_file = './result.html'
#执行方法四:匹配某个目录下所有以test开头的py文件,执行这些文件下的所有测试用例
test_dir = 'pytest_base/testcases'
disvcover = unittest.defaultTestLoader.discover(test_dir, pattern="test*.py")
#unittest.TextTestRunner(verbosity=2).run(disvcover)
with open(report_file ,"wb") as report:
runner = HTMLTestRunner(stream=report, title=report_title, description=desc)
runner.run(disvcover)
"""
测试用例执行过程:
1、写好测试用例
2、由TestLoader加载TestCase到TestSuite
3、由TextTestRunner来运行TestSuite
4、运行的结果保存在TextTestResult中
5、整个过程集成在unittest.main模块中
6、TestCase可以是多个,TestSuite也可以是多个
"""
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,977
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/test_allure_feature.py
|
"""
allure常用特性:
@allure.feature和@allure.story得关系:类似父与子得关系
feature相当于testsuite
story相当于testcase
allure-step
在app、web测试中,最好是每切换到一个新的页面当作一个step
用法:
--@allure.step(),以装饰器得形式放在类或者方法上面
--with allure.step()可以放在测试用例得方法里,但是测试步骤得代码需要被该语句包含
allure特性
"""
import allure
@allure.feature('登陆测试')
class TestLogin():
@allure.story('登陆成功')
def test_login_success(self):
print("这是登陆: 测试用例, 登陆成功")
pass
@allure.story('登陆成功')
def test_login_success_a(self):
print("这是登陆,测试用例, 登陆失败")
pass
@allure.story('用户名缺失')
def test_login_success_b(self):
print("用户名缺失")
pass
@allure.story('登陆过程之密码丢失')
def test_login_failure(self):
with allure.step("点击用户名"):
print("请输入用户名")
with allure.step("点击用户密码"):
print("请输入用户密码")
print("点击登录")
with allure.step("点击登录后登陆失败"):
print("登陆失败")
pass
@allure.story('登陆失败')
def test_login_ailure(self):
print("这是登陆,测试用例, 登陆失败")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,978
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/subdemo/conftest.py
|
import pytest
@pytest.fixture()
def connectDB():
print("这是 sub_demo下得 conftest")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,979
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/common/get_log.py
|
import datetime
import logging
import os
import configparser
class Log:
BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
"""
os.path.dirname(path):返回路径 path 的目录名称
os.path.realpath(file):返回指定文件的规范路径
"""
def __init__(self,name="logs"):
"""
param name: 生成器的名称
"""
#创建配置文件解析器实例cf
cf = configparser.ConfigParser()
self.log_name = name
#添加日志器
self.logger = logging.getLogger(name)
#设置日志级别
self.logger.setLevel(level=logging.INFO)
#设置日志格式
self.f1 = logging.Formatter(fmt='%(asctime)s %(filename)s %(lineno)d %(message)s')
"""
asctime:当前时间
filename:日志文件的名称
lineno:日志的当前行数
message:日志的信息
"""
self.f2 = logging.Formatter(fmt='%(asctime)s %(filename)s %(lineno)d >>>>>>> %(message)s')
#日志文件的名称
self.filename = 'BASE_PATH'
#添加一个控制台处理器
def add_StreamHandler(self):
#添加控制台处理器
self.handler = logging.StreamHandler()
#设置处理器的日志级别
self.handler.setLevel(level=logging.INFO)
#给处理器添加(日志输出)格式
self.handler.setFormatter(self.f1)
#日志器添加处理器,就拥有了屏幕输出的和文件输出的日志
self.logger.addHandler(self.handler)
#添加一个文件处理器
def add_FileHandler(self):
#生成日期。创建Log_2020-xx-xx.log文件
a = self.log_name + "_" + str(datetime.date.today()) + ".log"
#拼接log文件存放的文件夹和路径
b = os.path.join(self.BASE_PATH, "logs", a)
file_mode = self.cf
#添加文件处理器
self.filehand = logging.FileHandler()
#设置处理器的日志级别
self.filehand.setLevel(level=logging.INFO)
#处理器添加格式
self.filehand.setFormatter(self.f2)
#日志器添加处理器
self.logger.addHandler(self.filehand)
def get_log(self):
"""
运行创建文件处理器和流处理器的代码,最终返回一个logger对象
:return: logger对象
"""
#创建了文件处理器
self.add_StreamHandler()
#创建流处理器
self.add_FileHandler()
#返回记录器,拥有文件和流的处理器和格式,可以输出日志了
return self.logger
log = Log().get_log()
if __name__ == "__main__":
log.error("abc")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,980
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/api/address_model.py
|
#建立通讯录类,一套可维护得面向对象的东西
# 通讯录联系人的公共api类
import json
import requests
from interface_test_combat.api.base import Base
class Address(Base):
# url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwec359d0349cb57a1&corpsecret=JzhIasSlUFfz81kPlM-m1-qwSbG2JH4hQiZ1r6_2TqQ"
# r = requests.get(url)
# token = r.json()['access_token']
# def __init__(self):
# # 获取通讯录得token
# url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwec359d0349cb57a1&corpsecret=JzhIasSlUFfz81kPlM-m1-qwSbG2JH4hQiZ1r6_2TqQ"
# r = self.send("get",url)
# #res = requests.get(url)
# self.token = r['access_token']
def __init__(self):
Base.__init__(self)
def add_user(self, userid:str, name:str, mobile:str, department:list, **kwargs):
"""
增加联系人,这里代码没有封装,看起来很乱
:param token: token值
:param userid: 请求参数的值
:param name: 请求参数的值
:param mobile: 请求参数的值
:return: 返回响应体
"""
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/create"
body = {
"userid": userid,
"name": name,
#"alias": "Judy",
"mobile": mobile,
"department": department,
}
#将kwargs更新到body中
body.update(kwargs)
r = self.send("post", url,json=body)
#r = requests.post(url, json=body)
return r
def dele_user(self,userid):
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/delete?userid={userid}"
r = self.send("get", url)
#r = requests.get(url)
return r
def updata_user(self,userid,name,**kwargs):
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/update"
body = {
"userid": userid,
"name": name,
}
body.update(kwargs)
header = {'content-type': "application/json"}
r = self.send("post", url, data = json.dump(body), headers=header)
#r = requests.post(url, data=json.dumps(body), headers=header)
return r
def get_user(self,userid):
url = f"https://qyapi.weixin.qq.com/cgi-bin/user/get?userid={userid}"
r = self.send("get", url)
#r = requests.get(url)
return r
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,981
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_calcu_new.py
|
import pytest
import yaml
from decimal import Decimal
class TestCalc:
@pytest.mark.first
def test_add(self,get_calc,get_datas_add,all_start):
result = None
try:
#用fixture方法名返回计算器实例并调用计算器中的方法add
result = get_calc.add(get_datas_add[0], get_datas_add[1])
if isinstance(result,float):
result = round(result, 2)
except Exception as e:
print(e)
assert result == get_datas_add[2]
@pytest.mark.fourth
def test_div(self,get_calc,get_datas_div):
result = None
try:
result = get_calc.div(get_datas_div[0], get_datas_div[1])
except Exception as e_div:
print("division by zero")
assert result == get_datas_div[2]
@pytest.mark.second
def test_sub(self,get_calc,get_datas_sub):
result = None
try:
result = get_calc.sub(get_datas_sub[0],get_datas_sub[1])
if isinstance(result,float):
result = round(result, 2)
except Exception as e_sub:
print(e_sub)
assert result == get_datas_sub[2]
@pytest.mark.third
def test_mul(self,get_calc,get_datas_mul):
result = None
try:
result = get_calc.mul(get_datas_mul[0],get_datas_mul[1])
if isinstance(result,float):
result = round(result, 2)
except Exception as e_mul:
print(e_mul)
assert result == get_datas_mul[2]
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,982
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_cookie.py
|
#传递Cookie的两种方式:1、通过请求头信息传递 2、通过请求得关键字参数cookies传递
#通过自定义header传递
import requests
def test_demo():
url = "https://httpbin.testing-studio.com/cookies"
header = {"Cookie": "hogwarts=school",
'User-Agent': 'wow'}
r = requests.get(url = url,headers = header)
print(r.request.headers)
#使用cookies参数传递
def test_demo1():
url = "https://httpbin.testing-studio.com/cookies"
header = {'User-Agent': 'wow'}
cookie_data= {"hogwarts":"school",
"people":"teacher"}#需要是一个字典
r = requests.get(url = url,cookies = cookie_data,headers = header)
print(r.request.headers)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,983
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_calcu.py
|
import pytest
import yaml
import sys
from pytest_combat.testcases.test_param import get_datas
print(sys.path)
# sys.path.append("D:\pycharm\pythonproject\pytest_combat\api\calculator.py")
from pytest_combat.api.calculator import Calculator
class TestCal:
def setup_class(self):
self.calc = Calculator()
def setup_method(self):
print("开始计算")
def teardown_method(self):
print("结束计算")
@pytest.mark.parametrize(("a,b,expected"),get_datas()[0])
def test_add(self,a,b,expected):
result = self.calc.add(a,b)
assert result == expected
@pytest.mark.parametrize("a,b,expected",[(3,2,1),(1,2,-1)])
def test_sub(self,a,b,expected):
result1 = self.calc.sub(a,b)
assert result1 == expected
@pytest.mark.parametrize(("a, b,expected"),get_datas()[0])
def test_mul(self,a,b,expected):
result2 = self.calc.mul(a,b)
assert result2 == expected
@pytest.mark.parametrize("a,b,expected",[(3,1,3),(4,2,2)])
def test_div(self,a,b,expected):
result3 = self.calc.div(a,b)
assert result3 == expected
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,984
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_mulevn.py
|
"""
多环境下的接口测试,实现原理:
在请求之前,对请求的url进行替换
1、需要二次封装requests,对请求进行定制化
2、将请求的结构体的url从一个写死的IP地址改为一个(任意的)域名
3、使用一个evn配置文件,存放各个环境的配置信息
4、然后将请求结构体中url替换为‘evn'配置文件中个人选择的url
5、将evn配置文件使用yaml进行管理
"""
import requests
import yaml
class Api:
env = yaml.safe_load(open("env.yaml"))
#对请求进行二次封装,data是一个请求得信息
def send(self,data:dict):
data["url"] = str(data["url"]).replace("famliy.quickan.com",self.env["testing-studio"][self.env["default"]])
r = requests.request(method=data["method"] ,url=data["url"],headers=data["headers"])
return r
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,985
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_api.py
|
from interface_test_framework.testcases import test_mulevn
class TestApi:
data = {
"method": "get",
"url": "http://famliy.quickan.com:10000/demo64.txt",
"headers": None
}
def test_send(self):
res = test_mulevn.Api()
r = res.send(self.data)
print(r.text)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,986
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/baidu.py
|
hello = "hello baidu"
def search():
print("这是一个搜索方法")
def search1():
print("这还是一个搜索方法")
class SearchDemo:
pass
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,987
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/test.py
|
"""
分段函数求值
3x-5 (x>1)
f(x) = x+2 (-1<=x<=1)
5x +3 (x<-1)
"""
#分支结构
#x = -2
#if x > 1:
# y = 3*x-5
#elif x < -1:
# y = 5*x+3
#else:
# y = x+2
#print(y)
def calculate(x):
if x > 1:
y = 3*x-5
elif x < -1:
y = 5*x+3
else:
y = x+2
print(y)
calculate(2)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,988
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_auth.py
|
#如何通过auth传递认证信息
import requests
from requests.auth import HTTPBasicAuth
def test_oauth():
r = requests.get(url= "https://httpbin.testing-studio.com/basic-auth/string/1234",
auth = HTTPBasicAuth("string","1234"))
print(r)
print(r.text)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,989
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/test_allure_severity.py
|
import allure
import pytest
def test_with_no_severity_label():
pass
@allure.severity(allure.severity_level.TRIVIAL)
def test_with_trivial_severity():
print("用例等级是trivial")
pass
@allure.severity(allure.severity_level.NORMAL)
def test_with_normal_severity():
print("用例等级是normal")
pass
@allure.severity(allure.severity_level.NORMAL)
class TestClassWithNormalSeverity:
def test_inside_the_normal_severity_test_class(self):
print("inside the normal class")
pass
@allure.severity(allure.severity_level.CRITICAL)
def test_inside_the_normal_severity_test_class_with_overriding_critical_severity(self):
print("the_normal_severity_test_class_with_overriding_critical_severity")
pass
if __name__ == '__main__':
pytest.main()
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,990
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/pytest_plug.py
|
"""
pytest常用插件
pip install pytest-rerunfailures-----失败重跑--有些场景下重要的用例需要重跑,加装饰器
---pytest --reruns 5---指定失败用例重跑次数
---pytest --reruns 5 --reruns-delay 1---指定失败用例重跑次数以及每次重跑间隔时间
pip install pytest-assume------多重校验
---使用场景:一个方法中写有多条断言,中间有一条失败,后边的代码就不执行了;希望有失败也能执行完所有断言
---安装:pip install pytest-assume
---执行:pytest。assume(1==4);pytest.assume(2==4)
pip install pytest-ordering-----控制用例的执行顺序
--场景:对于继承测试,经常会有上下文依赖关系的测试用例
--安装:pip install pytest-ordering
--执行:@pytest.mark.run(order=2)
---case基本设计原则
------不要让case有顺序
-------不要让测试用例有依赖
-------如果无法做到,可以临时性的用插件解决
pip install pytest-xdist----分布式并发执行测试用例
场景:测试用例数庞大,执行需要时间太长
安装:pip install pytest-xdist
执行:pytest -n 3
分布式执行测试用例原则
--用例之间是独立的,用例之间没有依赖关系,用例可以完全独立运行
--用例执行没有顺序,随机顺序都能正常执行
--每人用例都能重复运行,运行结果不会影响其他用例
"""
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,991
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_param_fixture.py
|
import pytest
"""
通过fixture也可以实现参数化,不同的fixture传入测试用例中动态生成测试用例
"""
@pytest.fixture(params=[1,2,3],ids=['r1', 'r2', 'r3'])
def login1(request):
data = request.param
print("获取测试数据")
return data + 4
pass
def test_case1(login1):
#获取data数据
print(login1)
print("测试用例1")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,992
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_framework/testcases/test_request_info.py
|
"""
header的构造:
--普通的header:
----headers = {‘user-agent’:‘my-app/0.0.1)
----r = request.get(url,headers=headers)
--cookie
---cookies = dict(cookies_are='working')
----r = requests.get(url,cookies=cookies)
"""
import requests
class Test_Demo:
def test_get(self):
r = requests.get('https://httpbin.testing-studio.com/get')
print(r.status_code)
print(r.text)
print(r.json())
print(r.request)
assert r.status_code == 200
#get quary请求
def test_quary(self):
payload={
"a":1,
"name":"Lucy"
}
r = requests.get('https://httpbin.testing-studio.com/get',params=payload)
print(r.text)
assert r.status_code == 200
#form请求,常见一些表单,,常见登陆用户名和密码
def test_form(self):
payload = {
"level": 1,
"name": "lily"
}
r = requests.post('https://httpbin.testing-studio.com/post', data=payload)
print(r.text)
assert r.status_code == 200
#文件上传
def test_fileupload(self):
file = {'file':open('D:\pycharm\pythonproject\empty_book.xlsx','rb')}
r = requests.post('https://httpbin.testing-studio.com/post',files=file)
print(r.text)
assert r.status_code == 200
def test_heaser(self):
r = requests.get("https://httpbin.testing-studio.com/get",headers={"h":"header demo"})
print(r.status_code)
print(r.text)
print(r.json())
print(r.headers)
assert r.status_code == 200
assert r.json()['headers']['H'] == "header demo"
"""
响应结果
基本信息:r.url、r.status_code、r.headers、r.cookies
响应结果:
r.text=r.encoding+r.content
r.json()=r.encoding+r.content+content type json
r.raw.read(10)
对用的请求内容:r.request
"""
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,993
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/src/test_allure_link.py
|
"""
关联测试用例(可直接给测试用例得地址链接)
关联bug
---执行时需要加个参数
-----allure-link-pattern=issue:http://www.mytesttracker.com/issue.{}
"""
"""
按重要性级别进行一定范围测试
场景:
通常测试有P0、冒烟测试、验证上线测试。按照重要性级别来分别执行得,iru上线要把主流程和重要模块都跑一遍
解决:
通过附加pytest.mark标记
通过allure.feature,allure.story
也可以通过allure.severity来附加标记
级别:Trivial:不重要, Normal:正常问题, Critical:严重, Blocker:阻塞
步骤:
在方法、函数、类上面加
@allure.severity(allure.severity_level.TRIVIAL)
执行时
pytest -s -v 文件名 --allure-severities normal,critical
"""
import allure
@allure.link("http://www.baidu.com")
def test_with_link():
print("这是一条添加了链接得测试")
pass
TEST_CASE_LINK = 'http://www.baidu.com'
@allure.testcase(TEST_CASE_LINK, '测试用例')
def test_with_testcase_link():
print("这是一条测试用例的链接,连接到测试用例里边")
pass
#--allure-link-pattern=issue:http://www.baidu.com/{}
@allure.issue('140', '这是一个bug')
def test_with_issue_link():
pass
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,994
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/distribution/testcases/test_becommaster_success.py
|
import json
import requests
import pytest
from distribution.api.becom_master import BecomeMaster
from distribution.api.login_test import TestLogin
class TestBecomeMaster:
# def set_up(self):
# # s = requests.session()
# self.login = Login()
# self.becomemaster = BecomeMaster()
# # print(s)
# def test_login1(self):
# r1 = TestLogin.test_login()
# r1_1=r1.json()
# print(type(r1_1))
# print(r1_1)
# print(r1_1['code'])
# print(r1.cookies)
# assert (r1_1['code']) == 200
def test_become_master1(self):
res = TestLogin.test_login()
# print(res)
cookie = res.cookies
print(cookie)
r2 =BecomeMaster.become_master(cookie)
# print(r2)
assert (r2['success']) == 'true'
if __name__ == '__main__':
pytest.main()
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,995
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/demo.py
|
#系统内置模块
import sys
print(sys.path)
import os
import re
import json
import time
os.path
time.sleep()
#第三方开源模块,需使用pip install 模块名 进行安装
import yaml
import requests
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,996
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/func12_test.py
|
"""
第三方库
pytest
request
pypi.org 可搜索第三方库说明文档并了解
"""
import requests
res = requests.get("http://www.baidu.com")
print(res.status_code)
print(res.text)
payload = {'key1': 'value1', 'key2': 'value2'}
res1 = requests.post("http://httpbin.org/post", data=payload)
print(res1.text)
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,997
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_order.py
|
import pytest
@pytest.mark.run(order=2)
def test_a():
print("case 1")
@pytest.mark.run(order=3)
def test_b():
print("case 2")
@pytest.mark.run(order=1)
def test_c():
print("case 3")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,998
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_combat/testcases/test_scope.py
|
"""
定义:
@pytest.fixture()
def fixture_method():
print("setup")
yield 返回值
print("teardown")
调用方法
测试用例张传入fixture方法名
@pytest.mark.usefixture("fixture函数名称")
自动调用 @pytest.fixture(autouse=True)
作用域
控制方式:@pytest.fixture(scope="")
scope的取值
function 默认值
class
module
session
fixture方法返回值的获取
在测试用例中使用fixture方法名可以获取到yield后面的返回值
"""
import pytest
class TestDemo:
def test_a(self,connectDB):
print("testcase a")
def test_b(self):
print("testcase b")
class TestDemo2:
def test_a(self):
print("testcase a")
def test_b(self):
print("testcase b")
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,816,999
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/interface_test_combat/conftest.py
|
# import os
#
# import pytest
# import yaml
#
# from interface_test_combat.api.address_method import Address
# from interface_test_combat.requests_method import HttpRequest
#
#
# @pytest.fixture(scope="session")
# def get_request():
# print("获取请求方法实例")
# request_1= HttpRequest()
# return request_1
#
# @pytest.fixture(scope="class")
# def get_addr():
# print("获取通讯录方法实例")
# addr = Address()
# return addr
#
# @pytest.fixture(scope="class")
# def get_token(get_request):
# url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwec359d0349cb57a1&corpsecret=JzhIasSlUFfz81kPlM-m1-qwSbG2JH4hQiZ1r6_2TqQ"
# r = get_request.request(url=url,method="get")
# token = r.json()["access_token"]
# return token
#
#
#
# #通过 os.path.dirname 获取当前文件所在目录的路径
# yaml_file_path = os.path.dirname(__file__) + r"\user_data.yaml"
# print(yaml_file_path)
# with open(yaml_file_path,encoding='utf-8') as f:
# data = yaml.safe_load(f)#读取yaml文件中的数据赋给data变量
# #print(data)
# adduser_url = data["address"][0]['url']
# adduser_data = data["address"][0]['data']
# adduser_method = data["address"][0]['method']
#
# deleuser_url = data["address"][1]['url']
# deleuser_method = data["address"][1]['method']
#
# updateuser_url = data["address"][2]['url']
# updateuser_data = data["address"][2]['data']
# updateuser_method = data["address"][2]['method']
#
# getuser_url = data["address"][3]['url']
# getuser_method = data["address"][3]['method']
#
# # print(adduser_url)
# # print(adduser_data)
# # print(adduser_method)
#
# @pytest.fixture(params=[adduser_url,adduser_data,adduser_method])
# def get_adduser_data(request):
# data_add = []
# data_add = list(request.param)
# print(f"request.param得测试数据是:{data_add}")
# data_add = data_add.append(data_add)
# yield data_add # 返回传入的参数
#
# @pytest.fixture(params=[deleuser_url,deleuser_method])
# def get_deleuser_data(request):
# data_dele = request.param
# print(f"request.param得测试数据是:{data_dele}")
# yield data_dele # 返回传入的参数
#
#
# @pytest.fixture(params=[updateuser_url,updateuser_data,adduser_method])
# def get_updateuser_data(request):
# data_update = request.param
# print(f"request.param得测试数据是:{data_update}")
# yield data_update # 返回传入的参数
#
# @pytest.fixture(params=[getuser_url,getuser_method])
# def get_getuser_data(request):
# data_get = request.param
# print(f"request.param得测试数据是:{data_get}")
# yield data_get # 返回传入的参数
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,817,000
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/distribution/api/login_test.py
|
import pytest
import requests
class TestLogin:
@staticmethod
def test_login():
url = "https://api.quickcan.cn/v2/phone/signin"
payload = 'phone=13728814523&password=11111111w'
headers = {
'User-Agent': 'Kuaikan/5.93.1/593100(Android;6.0.1;OPPO R9s;kuaikan17;WIFI;1920*1080)',
'app-info': 'eyJLS0RJRCI6IkEyMDIwMDMyNzA5Mzk0OTc2MzYzNjEyMjg4Mzg1MDQ2IiwiYWVnaXNfYXBwX2lkIjoiMTAwMDAwMTI0MCIsImFuZHJvaWRfaWQiOiJkY2FkYTdjZWU3Yzg5YTYxIiwiYXBwX3NlY3JldF9zaWduIjoiOTY3NGMxNWY3YmY1ZGRiNGRiZjhiNGVlNjgyMTAyYWIiLCJiZCI6Ik9QUE8iLCJjYSI6MCwiY3QiOjIwLCJkZXZ0IjoxLCJkcGkiOjQ4MCwiZ3BzX3RpbWUiOjAsImhlaWdodCI6MTkyMCwiaW1laSI6Ijg2NDA4MDAzNTgzODU3OSIsImltc2kiOiIiLCJra19jX3QiOjE2MjE4NTE5NjczNDgsImtrX3NfdCI6MTYyMTg1MTk2NTE2MiwibWFjIjoiZTQ6NDc6OTA6Y2Q6OWU6YTMiLCJtb2RlbCI6Ik9QUE8gUjlzIiwib2FpZCI6IiIsIm92IjoiNi4wLjEiLCJwaG9uZU51bWJlciI6IiIsInVzZXJfZ3JvdXAiOiJub3JtYWwiLCJ2aXNpdG9yX3NpZ24iOiJiZGY2NzU5OWFmZWFmYzgzYTdmNTY0ZjdlNTZjNjc3YSIsIndpZHRoIjoxMDgwfQ==',
'x-device': 'A:dcada7cee7c89a61',
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.json())
print(response.cookies)
return response
if __name__ == '__main__':
pytest.main()
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,817,001
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/forTest/functiontest.py
|
"""
函数代码块以def 关键字开头,后接函数名称和圆括号()。
冒号起始
注意缩进
圆括号中定义参数
函数说明--文档字符串
return 【表达式】 结束函数
选择性的返回一个值给调用方
不带表达式的return 或者不写return函数,相当于返回None
函数的调用形式
调用时的传参
位置参数
"""
#函数的定义
#位置参数
def func1(a, b, c):
"""
函数func1的作用
:param a:参数a用来打印
:param b:
:param c:
:return:
"""
print("这是一个函数")
#pycharm快捷键 ctrl + d 复制一行代码
print("打印出变量a", a)
print("打印出变量b", b)
print("打印出变量c", c)
return a
#函数的调用
print(func1(1, 2, 3))
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,817,002
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/python_combat/src/hero_factory.py
|
#简单工厂方法
from python_combat.src.chengyaojin import ChengYaoJin
from python_combat.src.hero import Hero
from python_combat.src.libai import LiBai
from python_combat.src.log import log
class HeroFactory:
@classmethod
def creat_hero(cls, name:str) -> Hero:
if name == '程咬金':
return ChengYaoJin()
elif name == '李白':
return LiBai()
else:
log.error(f"don't know how to creat hero {name}")
return None
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,817,003
|
wangjinjin123/python_test_forme
|
refs/heads/main
|
/pytest_base/testcases/test_datadriven.py
|
"""
应用场景:
基于测试步骤的数据驱动
基于测试数据的数据驱动
基于配置的数据驱动:切换环境host 和 url地址时使用
"""
import pytest
import yaml
class TestDemo:
@pytest.mark.parametrize("env", yaml.safe_load(open("D:\pycharm\pythonproject\pytest_base\data\evn.yaml")))
def test_demo(self,env):
if "test" in env:
print("这是测试环境")
print(env)
print("测试环境的ip是:",env["test"])
elif "dev" in env:
print("这是开发环境")
print("开发环境的ip是:", env["test"])
|
{"/interface_test_combat/common/mysql.py": ["/interface_test_combat/common/config.py", "/interface_test_combat/common/get_log.py"], "/interface_test_combat/testcases/test_address_1.py": ["/interface_test_combat/api/address_model.py"], "/demo1.py": ["/baidu.py"], "/interface_test_combat/path_data.py": ["/interface_test_combat/api/address_model.py"], "/pytest_combat/testcases/test_calcu.py": ["/pytest_combat/testcases/test_param.py"], "/distribution/testcases/test_becommaster_success.py": ["/distribution/api/becom_master.py", "/distribution/api/login_test.py"]}
|
27,833,021
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/reader.py
|
import csv
import zipfile
import xlrd
import os
class Reader(object):
def __init__(self, filePath):
self.filePath = filePath
def read(self): #父类先实现该方法
pass
class CsvReader(Reader):
def __init__(self, filePath):
self.filePath = filePath
def read(self) -> list:
with open(self.filePath, mode="r", encoding="utf-8") as csvfile:
csvReader = csv.reader(csvfile)
rowsData = [row for row in csvReader]
return rowsData
class XlsReader(Reader):
rowAllValues = []
nrows = 0
def __init__(self, filePath, sheetIndex):
self.filePath = filePath
self.sheetIndex = sheetIndex
def read(self) -> list:
with xlrd.open_workbook(self.filePath) as xlsFile:
xlsSheet = xlsFile.sheet_by_index(self.sheetIndex) #打开指定的表
self.nrows = xlsSheet.nrows
print(type(xlsSheet.row_values(0)))
for i in range(self.nrows):
self.rowAllValues.append(xlsSheet.row_values(i))
return self.rowAllValues
class ZipReader(Reader):
def __init__(self, filePath, interFileName):
self.filePath = filePath
self.interName = interFileName
def read(self) -> list:
with zipfile.ZipFile(self.filePath, "r") as zip:
folder,fileName = os.path.split(self.filePath)
print(folder)
zip.extract(self.interName, folder) #解压指定文件
if (".csv" in self.interName):
return CsvReader(folder+'\{0}'.format(self.interName)).read()
elif (".xls" in self.interName):
return XlsReader(folder+'\{0}'.format(self.interName), 0).read()
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,022
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Ui_Joseph/main/main.py
|
import reader
from PyQt5.QtWidgets import *
from ui import JosephUi
import sys
if __name__ == "__main__":
choice = int(input("请输入你想选择何种界面(1:QT界面 2:控制台界面):"))
if choice == 1:
app = QApplication(sys.argv)
myWin = JosephUi.MyMainForm()
myWin.show()
sys.exit(app.exec_())
else:
JosephUi.MyConsoleUi().buildUi()
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,023
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/unitTest.py
|
from datetime import date
import unittest
import reader
import Joseph05_date_7_14
# 缺乏测试经验不知道测些啥
class CsvReaderFunctionTest(unittest.TestCase):
def testFunctionCsvRead(self):
data = reader.CsvReader("G:\python\csvdemo1.csv").read()
print(len(data))
self.assertEqual(len(data), 53)
for i in range(50):
self.assertEqual(data[i][0], "潘{0}号".format(i + 1))
#self.assertNotAlmostEqual(type(data), lui)
class XlsReaderFunctionTest(unittest.TestCase):
def testFunctionXlsRead(self):
data = reader.XlsReader("G:\python\csvdemo1.xls", 0).read()
self.assertEqual(len(data), 100)
for i in range(50):
self.assertEqual(data[i][0], "潘{0}号".format(i + 1))
class ZipReaderFunctionTest(unittest.TestCase):
def testFunctionZipRead(self):
data = reader.ZipReader("G:\python\csvdemo1.zip", "csvdemo1.xls").read()
self.assertEqual(len(data), 150)
for i in range(50):
self.assertEqual(data[i][0], "潘{0}号".format(i + 1))
class JosephFunctionTest(unittest.TestCase):
def testFunctionJosephCricle(self):
obj = Joseph05_date_7_14.JosephCricle(reader.ZipReader("G:\python\csvdemo1.zip", "csvdemo1.xls").read(), 1, 20, 2).getJosephCricle()
self.assertEqual(type(obj), list)
self.assertEqual(obj[19].Id, 9)
unittest.main()
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,024
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Joseph.py
|
'''第一个版本:实现了基本的约瑟夫环任务'''
def JosephCalculate(maxNum, stepNum):
"""加上断言,养成良好习惯"""
assert maxNum > 0
assert stepNum > 0
data = []
delData = []
num = 0
for i in range(1, maxNum + 1):
data.append(i)
while len(data) > 1:
num += 1
temp = data.pop(0) #取出头部
if num == stepNum:
print(num)
delData.append(temp)
num = 0
else:
data.append(temp) #是个环,头变尾部
return {'lastData':data[0], 'delData':delData} #返回一个字典
def JosephCalculate1(maxNum, stepNum):
pos = 0
for i in range(1, maxNum + 1):
pos = (pos + stepNum) % i
return pos + 1
if __name__ == '__main__':
result = JosephCalculate(43, 3)
print('最后淘汰的是第', result['lastData'],'人')
print('淘汰的人的序号为',result['delData'])
print("最后淘汰的序号为", JosephCalculate1(41, 3))
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,025
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/005.py
|
import os
from PIL import Image
imageWidth = 1136
imageHeight = 640
fileinfo = "G:/python/practise/"
mylist = os.listdir(fileinfo)
# resize方法是返回修改后的对象
for n in mylist:
if (".jpg" in n or ".png" in n):
im = Image.open(fileinfo+n)
out = im.resize((imageWidth, imageHeight))
out.save('new'+n)
print(n)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,026
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Joseph02.py
|
'''date:2021-7-7
author:潘水根
第二个版本:这个版本把学生对象容器作为传入参数,基本传入参数有起始序号,步长,总人数,实现第二次布置的约瑟夫环的基本任务
'''
data = []
# 创建学生类
class Student():
def __init__(self, name, schoolId, Id):
self.name = name
self.schoolId = schoolId
self.Id = Id
def sayHello(self):
print("Hi nice to meet you. i am {0}".format(self.name))
def getStudentObject(maxNum):
for i in range(1, maxNum + 1):
strName = ""
strId = ""
# print(i)
strName = "潘{0}号".format(i)
strId = "20170710{0}".format(i)
data.append(Student(strName, strId, i))
#print(data[i - 1].name)
#print(data[i - 1].schoolId)
return data
def JosephCalculate(studentObj, startNum, maxNum, stepNum):
"""加上断言,养成良好习惯"""
assert maxNum > 0
assert stepNum > 0
assert startNum > 0
calData = []
delData = []
num = 0
startNumCopy = startNum
for i in range(startNum, len(studentObj) + 1, 1):
calData.append(studentObj[i - 1])
for x in range(startNumCopy - 1):
calData.append(studentObj[x])
#for i in range(len(calData)):
#print(calData[i].Id)
print(len(calData))
print(len(studentObj))
studentObj = calData.copy()
while len(studentObj) > 1:
num += 1
temp = studentObj.pop(0)
if num == stepNum:
delData.append(temp)
num = 0
else:
studentObj.append(temp)
return {'lastData':studentObj[0], 'deldata':delData}
if __name__ == '__main__':
delDataShow = []
startNum = int(input("请输入开始序号:"))
maxNum = int(input("请输入总人数:"))
stepNum = int(input("请输入步长值:"))
studentObj = getStudentObject(maxNum)
result = JosephCalculate(studentObj, startNum, maxNum, stepNum)
print('最后淘汰的人的序号为:', result['lastData'].Id)
print('最后淘汰的人的学号为:', result['lastData'].schoolId)
print('最后淘汰的人的姓名为:', result['lastData'].name)
result['lastData'].sayHello()
for i in range(len(result['deldata'])):
delDataShow.append(result['deldata'][i].Id)
print('依次淘汰的人序号为:',delDataShow)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,027
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/001.py
|
from PIL import Image, ImageDraw, ImageFont
#用到了2D绘图模块 PIL
def AddWordToImage(word):
img = Image.open('001.jpg')
canvas = ImageDraw.Draw(img)
fontinfo = ImageFont.truetype('c:/windows/Fonts/Arial.ttf', size = 100)
fillcolor = "#ff0000" #红色
width, height = img.size
pos = (width - 220, 40)
canvas.text(pos, word, font=fontinfo,fill=fillcolor)
img.save('001r.jpg','jpeg')
if __name__ == '__main__':
AddWordToImage('8')
print("hello world")
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,028
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/0010.py
|
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母:
class Captcha(object):
def __init__(self, width, height):
assert width > 0
assert height > 0
self.width = width
self.height = height
def getBackRandChar(self):
return chr(random.randint(65, 90))
def getBackRandColor(self):
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
def getBackWorkRandColor(self):
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
def createCaptcha(self):
image = Image.new('RGB', (self.width, self.height), (255, 255, 255))
#创建字体对象
font = ImageFont.truetype('C:/windows/fonts/Arial.ttf', 36)
canvas = ImageDraw.Draw(image)
for x in range(self.width):
for y in range(self.height):
canvas.point((x, y), fill = self.getBackRandColor())
for i in range(4):
canvas.text((60 * i + 10, 10), self.getBackRandChar(), font=font, fill=self.getBackWorkRandColor())
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
if __name__ == '__main__':
captcha = Captcha(240, 60)
captcha.createCaptcha()
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,029
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/0012.py
|
#coding "utf-8"
splitdata = []
def dealSensitiveWord(filepath):
with open(filepath, "r", encoding="UTF-8") as file:
data = file.read()
splitdata = data.split("\n")
print(splitdata)
file.close()
while True:
replace = ""
chatData = input("请您输入你需要输入的内容:")
for data in splitdata:
if (data in chatData):
for i in range(len(data)):
replace += "*"
chatData = chatData.replace(data, replace)
print("have find {0}".format(chatData))
break
if __name__ == '__main__':
filepath = input("请您输入需要打开的文件地址:")
dealSensitiveWord(filepath)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,030
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/0014.py
|
import xlwt
from xlwt.Worksheet import Worksheet
def addTxtToExcel(filePath):
workSpace = xlwt.Workbook(encoding="utf-8") # 创建一个excel表格
workSheet = workSpace.add_sheet("sheet0") # 添加表格
with open(filePath, "r", encoding="utf-8") as txtFile:
txtData = txtFile.read()
print(txtData)
txtDataDict = eval(txtData) # 将读出的字符串数据转换成Dict
keyList = [str(i) for i in txtDataDict]
for i in range(len(keyList)):
workSheet.write(i, 0, keyList[i])
for i in range(len(keyList)):
for j in range(1, len(txtDataDict[keyList[i]]) + 1):
workSheet.write(i, j, txtDataDict[keyList[i]][j - 1])
workSpace.save("test2.xls")
if __name__ == '__main__':
filePath = input("请输入要打开TXT文件的路径:")
addTxtToExcel(filePath)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,031
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/004.py
|
import re
# 正则表达式库
def getWordNum(place):
num = 0
with open(place,'r') as f:
data = f.read()
result = re.split("[^a-zA-Z]", data) # 以字母以外的任意字符分割字符串
print(result)
for i in result:
if i != ' ':
num += len(i)
return num
if __name__ == '__main__':
print(getWordNum('G:/python/practise/004.txt'))
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,032
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Joseph04.py
|
'''date:2021-7-7
author:潘水根
第四个版本:这个版本加上了作业里发散的功能,把约瑟夫环封装成了一个容器,用for循环遍历环,同时目标对象从不同文件中获取
'''
import csv
import xlrd
import zipfile
data = []
# 创建学生类
class Student():
def __init__(self, name, schoolId, Id):
self.name = name
self.schoolId = schoolId
self.Id = Id
def sayHello(self):
print("Hi nice to meet you. i am {0}".format(self.name))
class Reader(object):
def __init__(self, filePath):
self.filePath = filePath
def openfile(self):
pass
# 读取Csv后缀文件
class CsvReader(Reader):
def __init__(self, filePath):
super().__init__(filePath)
self.filePath = filePath
def openCsvFile(self, maxNum) -> list:
with open(self.filePath, mode="r", encoding="utf-8") as csvfile:
csvReader = csv.reader(csvfile)
rowsData = [row for row in csvReader]
assert maxNum < len(rowsData) # 必须小于行数
for i in range(1, maxNum + 1):
data.append(Student(rowsData[i - 1][0], rowsData[i - 1][1], i))
return data
# 读取 Xls文件
class XlsReader(Reader):
def __init__(self, filePath):
super().__init__(filePath)
self.filePath = filePath
def openXlsFile(self, maxNum) -> list:
with xlrd.open_workbook_xls(self.filePath) as xlsfile:
xlsSheet = xlsfile.sheets()[0] # 打开第一张表
nrows = xlsSheet.nrows # 得到行数
assert maxNum < nrows
for i in range(1, maxNum + 1):
data.append(Student(xlsSheet.row_values(i - 1)[0], xlsSheet.row_values(i - 1)[1], i))
return data
# 读取 Zip压缩文件
class ZipReader(Reader):
pos = 0
strpos = ""
pathBase = ""
def __init__(self, filePath, filePathBase):
super().__init__(filePath)
self.filePath = filePath
self.filePathBase = filePathBase
def openZipFile(self, maxNuM) -> list:
with zipfile.ZipFile(self.filePath, 'r') as zip:
self.pos = zip.namelist()[0].index('.') # 默认只有一个文件
self.strpos = zip.namelist()[0][self.pos:]
zip.extractall(self.filePathBase)
print(self.strpos)
if (self.strpos == '.csv'):
print('OK')
print(self.filePathBase + '.{0}'.format(zip.namelist()[0]))
return CsvReader(self.filePathBase + '\{0}'.format(zip.namelist()[0])).openCsvFile(maxNuM)
elif (self.strpos == '.xls'):
return XlsReader(self.filePath + '\{0}'.format(zip.namelist()[0])).openXlsFile(maxNuM)
def getStudentObject(maxNum):
for i in range(1, maxNum + 1):
strName = ""
strId = ""
# print(i)
strName = "潘{0}号".format(i)
strId = "20170710{0}".format(i)
data.append(Student(strName, strId, i))
# print(data[i - 1].name)
# print(data[i - 1].schoolId)
return data
def JosephCalculate(studentObj, startNum, maxNum, stepNum) -> list:
"""加上断言,养成良好习惯"""
assert maxNum > 0
assert stepNum > 0
assert startNum > 0
calData = []
delData = []
num = 0
startNumCopy = startNum
# 根据开始序号重新排序
for i in range(startNum, len(studentObj) + 1, 1):
calData.append(studentObj[i - 1])
for x in range(startNumCopy - 1):
calData.append(studentObj[x])
# for i in range(len(calData)):
# print(calData[i].Id)
# print(len(calData))
# print(len(studentObj))
studentObj = calData.copy()
while len(studentObj) > 1:
num += 1
temp = studentObj.pop(0)
if num == stepNum:
delData.append(temp)
num = 0
else:
studentObj.append(temp)
# delData.append(studentObj[0])
# print(studentObj[0])
# print(delData[-1])
return [delData, studentObj[0]] # 封装成容器
if __name__ == '__main__':
delDataShow = []
startNum = int(input("请输入开始序号:"))
maxNum = int(input("请输入总人数:"))
stepNum = int(input("请输入步长值:"))
filePath = input("请输入文件路径:")
filePathBase = input("请输入文件根目录:")
# 单独打开CSV文件
# studentObj = CsvReader(filePath).openCsvFile(maxNum)
# 单独打开XLS文件
# studentObj = XlsReader(filePath).openXlsFile(maxNum)
# 单独打开zip文件
studentObj = ZipReader(filePath, filePathBase).openZipFile(maxNum)
# result = JosephCalculate(studentObj, startNum, maxNum, stepNum)
for obj in JosephCalculate(studentObj, startNum, maxNum, stepNum)[0]:
print("依次淘汰的人的序号为:{0}, 姓名为: {1}, 学号为:{2}".format(obj.Id, obj.name, obj.schoolId))
obj = JosephCalculate(studentObj, startNum, maxNum, stepNum)[1]
print("最后留下的人的序号为:{0}, 姓名为: {1}, 学号为:{2}".format(obj.Id, obj.name, obj.schoolId))
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,033
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Ui_Joseph/user_case/Joseph06.py
|
import reader
class Student():
def __init__(self, name, schoolId, Id):
self.name = name
self.schoolId = schoolId
self.Id = Id
def sayHello(self):
print("Hi nice to meet you. i am {0}".format(self.name))
class JosephCricle(object):
_objList = [] #对象列表
_originObjList = []
delObjList = []
def __init__(self, reader, startId, maxNum, stepNum):
self.startId = startId
self.maxNum = maxNum
self.stepNum = stepNum
self.fileData = reader
assert stepNum >= 0
assert startId >= 0
# 在约瑟夫环对象创建时就实例化学生对象
for i in range(0, self.maxNum):
self._objList.append(Student(self.fileData[i][0], self.fileData[i][1], i)) #得到学生娃儿的所有实例化对象
def __iter__(self):
return self
def __next__(self):
if len(self._objList) > 0:
outPos = (self.startId+self.stepNum - 1) % len(self._objList)
outStudent = self._objList.pop(outPos)
self.startId = outPos
return outStudent
else:
raise StopIteration
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,034
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/file.py
|
# coding=utf-8
def read_in_chunks(filepath, chunk_size = 1024):
file_object = open(filepath, "r")
while True:
file_data = file_object.read(chunk_size)
if not file_data:
break
yield file_data #调用生成器
if __name__ == '__main__':
filepath = input("请输入你需要打开文件的位置:")
str = ""
file = open('E:/360MoveData/Users/江西水根/Desktop'+"/3.txt", 'x')
for chunks in read_in_chunks(filepath):
str += chunks
file.write(str)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,035
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Ui_Joseph/ui/JosephUi.py
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from user_case import Joseph06, reader
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(640, 561)
self.verticalLayoutWidget = QtWidgets.QWidget(Form)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(80, 20, 471, 451))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.spinBox = QtWidgets.QSpinBox(self.verticalLayoutWidget)
self.spinBox.setObjectName("spinBox")
self.gridLayout.addWidget(self.spinBox, 1, 0, 1, 1)
self.fileDirLineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.fileDirLineEdit.setObjectName("fileDirLineEdit")
self.gridLayout.addWidget(self.fileDirLineEdit, 0, 2, 1, 1)
self.savePushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.savePushButton.setObjectName("savePushButton")
self.gridLayout.addWidget(self.savePushButton, 2, 0, 1, 1)
self.openFileButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.openFileButton.setObjectName("openFileButton")
self.gridLayout.addWidget(self.openFileButton, 0, 0, 1, 1)
self.textBrowser = QtWidgets.QTextBrowser(self.verticalLayoutWidget)
self.textBrowser.setObjectName("textBrowser")
self.gridLayout.addWidget(self.textBrowser, 4, 0, 1, 3)
self.calPushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.calPushButton.setObjectName("calPushButton")
self.gridLayout.addWidget(self.calPushButton, 2, 2, 1, 1)
self.mesInputLineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.mesInputLineEdit.setObjectName("mesInputLineEdit")
self.gridLayout.addWidget(self.mesInputLineEdit, 1, 2, 1, 1)
self.josephDataInputEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.josephDataInputEdit.setObjectName("josephDataInputEdit")
self.gridLayout.addWidget(self.josephDataInputEdit, 3, 0, 1, 1)
self.inputInterFilename = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.inputInterFilename.setObjectName("inputInterFilename")
self.gridLayout.addWidget(self.inputInterFilename, 3, 2, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.mesInputLineEdit.setPlaceholderText(_translate("Form", "请按照格式输入(姓名,学号)"))
self.savePushButton.setText(_translate("Form", "保存"))
self.openFileButton.setText(_translate("Form", "打开文件"))
self.fileDirLineEdit.setPlaceholderText(_translate("Form", "文件路径"))
self.calPushButton.setText(_translate("Form", "计算"))
self.josephDataInputEdit.setPlaceholderText(_translate("Form", "按格式输入:(开始序号,总人数,步长值)"))
self.inputInterFilename.setPlaceholderText(_translate("Form", "请输入要打开内部文件名"))
class MyMainForm(QMainWindow, Ui_Form):
reader = []
def __init__(self, parent=None):
super(MyMainForm, self).__init__(parent)
self.setupUi(self)
# 建立信号和槽的绑定
self.openFileButton.clicked.connect(self.openFile)
self.savePushButton.clicked.connect(self.saveDataToFile)
self.calPushButton.clicked.connect(self.calJosePh)
def fileDataShow(self):
self.textBrowser.clear()
for i in self.reader: # 更新显示方法
self.textBrowser.append(str(i))
def openFile(self):
# 要供外部使用的才写到属性里头
self.filenamePath, ok = QFileDialog.getOpenFileName(self, "选取单个文件", "c:/",
"All Files (*);;Text Files (*.txt)")
if (ok):
self.fileDirLineEdit.setText(str(self.filenamePath))
if ".csv" in self.filenamePath: #打开的是CSV文件
self.obj = reader.CsvReader(self.filenamePath) #对象也得设置成属性外部要使用
self.reader = self.obj.read()
self.fileDataShow()
if ".xls" in self.filenamePath:
self.obj = reader.XlsReader(self.filenamePath, "Sheet1")
self.reader = self.obj.read()
self.fileDataShow()
if ".zip" in self.filenamePath:
self.interFilename = self.inputInterFilename.text()
self.obj = reader.ZipReader(self.filenamePath, self.interFilename)
self.reader = self.obj.read()
self.fileDataShow()
def saveDataToFile(self):
self.mesInputData = self.mesInputLineEdit.text()
self.mesList = self.mesInputData.split(",")
self.index = self.spinBox.value()
self.reader[self.index][0] = self.mesList[0]
self.reader[self.index][1] = self.mesList[1]
self.obj.saveFile(self.reader)
self.fileDataShow()
def calJosePh(self):
dataList = self.josephDataInputEdit.text().split(",")
dataList = list(map(int, dataList))
startId = dataList[0] #开始值
maxNum = dataList[1]
stepNum = dataList[2]
print("the data is {0}, {1}, {2}".format(startId,maxNum,stepNum))
self.textBrowser.clear()
for obj in Joseph06.JosephCricle(self.reader, startId, maxNum, stepNum): # for循环遍历整个约瑟夫环
self.textBrowser.append("依次删除的同学的姓名为:{0},学号为:{1},序号为:{2}".format(obj.name, obj.schoolId, obj.Id))
class MyConsoleUi(object):
def __init__(self):
pass
def buildUi(self):
while True:
print("*****************这是开始******************")
filepath = input("请输入需要打开的文件路径:")
while True:
if filepath.endswith(".csv"):
print("***********您打开的是csv表格文件*********************")
obj = reader.CsvReader(filepath)
readerData = obj.read()
command = int(input("请问您现在需要干什么(1:输出表格数据 2:编辑表格数据 3:计算约瑟夫环 4:退出)请根据意愿进行选择,祝您愉快:"))
if command == 1:
print("***********为您输出表格内部数据***********************")
for i in range(len(readerData)):
print("学生的姓名为:{0},学号为:{1}".format(readerData[i][0], readerData[i][1]))
elif command == 2:
print("**************现在您想编辑信息*****************")
data = input("请按格式输入(序号,姓名,学号):")
str = data.split(",")
readerData[int(str[0])][0] = str[1]
readerData[int(str[0])][1] = str[2] # 得到需要保存的数据
obj.saveFile(readerData)
elif command == 3:
josephInfo = input("请您输入对应的开始序号,总人数,步长值。请按格式输入(开始序号,总人数,步长值):")
infoList = josephInfo.split(",")
startId = int(infoList[0])
maxNum = int(infoList[1])
stepNum = int(infoList[2])
print("******************现在为您输出约瑟夫环数据****************")
for stuobj in Joseph06.JosephCricle(readerData, startId, maxNum, stepNum): # for循环遍历整个约瑟夫环
print("依次删除的同学的姓名为:{0},学号为:{1},序号为:{2}".format(stuobj.name, stuobj.schoolId, stuobj.Id))
else:
break
else:
break
while True:
if filepath.endswith(".xls"):
print("***********您打开的是xls表格文件*********************")
obj = reader.XlsReader(filepath, "Sheet1")
readerData = obj.read()
command = int(input("请问您现在需要干什么(1:输出表格数据 2:编辑表格数据 3:计算约瑟夫环 4:退出)请根据意愿进行选择,祝您愉快:"))
if command == 1:
print("***********为您输出表格内部数据***********************")
for i in range(len(readerData)):
print("学生的姓名为:{0},学号为:{1}".format(readerData[i][0], readerData[i][1]))
elif command == 2:
print("**************现在您想编辑信息*****************")
data = input("请按格式输入(序号,姓名,学号):")
str = data.split(",")
readerData[int(str[0])][0] = str[1]
readerData[int(str[0])][1] = str[2] # 得到需要保存的数据
obj.saveFile(readerData)
elif command == 3:
josephInfo = input("请您输入对应的开始序号,总人数,步长值。请按格式输入(开始序号,总人数,步长值):")
infoList = josephInfo.split(",")
startId = int(infoList[0])
maxNum = int(infoList[1])
stepNum = int(infoList[2])
print("******************现在为您输出约瑟夫环数据****************")
for stuobj in Joseph06.JosephCricle(readerData, startId, maxNum, stepNum): # for循环遍历整个约瑟夫环
print("依次删除的同学的姓名为:{0},学号为:{1},序号为:{2}".format(stuobj.name, stuobj.schoolId, stuobj.Id))
else:
break
else:
break
while True:
if filepath.endswith(".zip"):
print("***********您打开的是zip压缩包文件*********************")
obj = reader.ZipReader(filepath, "demo6.csv")
readerData = obj.read()
command = int(input("请问您现在需要干什么(1:输出表格数据 2:计算约瑟夫环 3:退出)请根据意愿进行选择,祝您愉快:"))
if command == 1:
print("***********为您输出表格内部数据***********************")
for i in range(len(readerData)):
print("学生的姓名为:{0},学号为:{1}".format(readerData[i][0], readerData[i][1]))
elif command == 2:
josephInfo = input("请您输入对应的开始序号,总人数,步长值。请按格式输入(开始序号,总人数,步长值):")
infoList = josephInfo.split(",")
startId = int(infoList[0])
maxNum = int(infoList[1])
stepNum = int(infoList[2])
print("******************现在为您输出约瑟夫环数据****************")
for stuobj in Joseph06.JosephCricle(readerData, startId, maxNum, stepNum): # for循环遍历整个约瑟夫环
print("依次删除的同学的姓名为:{0},学号为:{1},序号为:{2}".format(stuobj.name, stuobj.schoolId, stuobj.Id))
else:
break
else:
break
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,036
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/002.py
|
import random
#常量大写
def getRandomStr(length = 8): #8位长度
str = ""
for i in range(length):
str += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
return str
actCode = [] #创建一个列表
if __name__ == '__main__':
for num in range(200):
actCode.append(getRandomStr(8))
print(actCode)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,037
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Joseph05_date_7_14.py
|
import reader
class Student():
def __init__(self, name, schoolId, Id):
self.name = name
self.schoolId = schoolId
self.Id = Id
def sayHello(self):
print("Hi nice to meet you. i am {0}".format(self.name))
class JosephCricle(object):
_objList = [] #对象列表
_originObjList = []
delObjList = []
def __init__(self, reader, startId, maxNum, stepNum):
self.startId = startId
self.maxNum = maxNum
self.stepNum = stepNum
self.fileData = reader
assert stepNum > 0
assert startId > 0
# 在约瑟夫环对象创建时就实例化学生对象
for i in range(1, self.maxNum + 1):
self._objList.append(Student(self.fileData[i - 1][0], self.fileData[i - 1][1], i)) #得到学生娃儿的所有实例化对象
def getJosephCricle(self):
startIdCopy = self.startId
num = 0
for i in range(self.startId, len(self._objList) + 1, 1):
self._originObjList.append(self._objList[i - 1])
for j in range(startIdCopy - 1):
self._originObjList.append(self._objList[j])
self._objList = self._originObjList.copy()
while len(self._objList) > 1:
num += 1
temp = self._objList.pop(0)
if num == self.stepNum:
self.delObjList.append(temp)
num = 0
else:
self._objList.append(temp)
self.delObjList.append(self._objList[0]) #最后留下的人也要加上
return self.delObjList #把依次删除的人返回
if __name__ == '__main__':
startNum = int(input("请输入开始序号:"))
maxNum = int(input("请输入总人数:"))
stepNum = int(input("请输入步长值:"))
filePath = input("请输入文件路径:")
interFileName = input("请输入需要解压缩文件名字:")
#obj = reader.XlsReader(filePath, 0) #excel格式实现
#reader = obj.read()
#obj = reader.CsvReader(filePath) #Csv表格格式实现
#reader = obj.read()
obj = reader.ZipReader(filePath, interFileName) #压缩包方式实现
reader = obj.read()
#josephObjList = JosephCricle(reader, startNum, maxNum, stepNum).getJosephCricle()
for obj in JosephCricle(reader, startNum, maxNum, stepNum).getJosephCricle(): #for循环遍历整个约瑟夫环
print("依次删除的学生姓名为:{0},学号为:{1},序号为:{2}".format(obj.name, obj.schoolId, obj.Id))
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,038
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/Ui_Joseph/user_case/reader.py
|
import csv
import zipfile
import xlrd
import os #pandas 这个库好用
import pandas as pd
class Reader(object):
def __init__(self, filePath):
self.filePath = filePath
def read(self): #父类先实现该方法
pass
class CsvReader(Reader):
def __init__(self, filePath):
assert filePath.endswith('.csv')
self.filePath = filePath
def read(self) -> list:
csvFile = pd.read_csv(self.filePath)
csvDataList = csvFile.values.tolist()
return csvDataList
def saveFile(self, dataList): #保存数据
df = pd.DataFrame(dataList)
df.to_csv(self.filePath,index=False)
class XlsReader(Reader):
def __init__(self, filePath, sheetName):
assert filePath.endswith('.xls')
self.filePath = filePath
self.sheetName = sheetName
def read(self) -> list:
xlsFile = pd.read_excel(self.filePath, sheet_name=self.sheetName)
xlsDataList = xlsFile.values.tolist()
return xlsDataList
def saveFile(self, dataList):
df = pd.DataFrame(dataList)
df.to_excel(self.filePath, index=False)
class ZipReader(Reader):
def __init__(self, filePath, interFileName):
assert filePath.endswith('.zip')
assert interFileName.endswith('.csv') or interFileName.endswith('.xls')
self.filePath = filePath
self.interName = interFileName
def read(self) -> list:
with zipfile.ZipFile(self.filePath, "r") as zip:
folder,fileName = os.path.split(self.filePath)
print(folder)
zip.extract(self.interName, folder) #解压指定文件
if (".csv" in self.interName):
return CsvReader(folder+'\{0}'.format(self.interName)).read()
elif (".xls" in self.interName):
return XlsReader(folder+'\{0}'.format(self.interName), "Sheet1").read()
def saveFile(self): #压缩包里的文件不能随便改变, 为了保持程序的完整性,加上
pass
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
27,833,039
|
LXwolf123/python-2021-7
|
refs/heads/main
|
/0011.py
|
#coding "utf-8"
splitdata = []
def dealSensitiveWord(filepath):
with open(filepath, "r", encoding="UTF-8") as file:
data = file.read()
splitdata = data.split("\n")
print(splitdata)
file.close()
while True:
chartData = input("请您输入你需要输入的内容:")
if (chartData in splitdata):
print("Freedom")
else:
print("Human Rights")
if __name__ == '__main__':
filepath = input("请您输入需要打开的文件地址:")
dealSensitiveWord(filepath)
|
{"/Ui_Joseph/main/main.py": ["/reader.py"], "/unitTest.py": ["/reader.py", "/Joseph05_date_7_14.py"], "/Ui_Joseph/user_case/Joseph06.py": ["/reader.py"], "/Joseph05_date_7_14.py": ["/reader.py"]}
|
28,055,529
|
junankim18/sinchon
|
refs/heads/master
|
/sumda/views.py
|
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from django.utils import timezone
from .forms import SignupForm, CommentForm
import json
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.http import JsonResponse
from urllib.parse import urlparse
from .models import *
def main(request):
posts = Diary.objects.all()
user = request.user
try:
profile = Profile.objects.get(user=user)
posts = Diary.objects.filter(profile=profile)
ctx = {
'posts_list': posts
}
except:
ctx = {}
return render(request, 'main.html', ctx)
def detail(request, pk):
post = get_object_or_404(Diary, pk=pk)
unknown_profile = post.profile
unknown_user = unknown_profile.user
comment_list = Comment.objects.filter(diary=post)
if request.method == 'POST':
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.diary = post
comment.save()
return redirect('/detail/'+str(pk))
else:
comment_form = CommentForm()
ctx = {
'post': post,
'comment_list': comment_list,
'comment_form': comment_form,
'unknown_user': unknown_user
}
return render(request, 'detail.html', ctx)
def send(request):
recieved_diary = Diary.objects.filter(receiver=None)
recieved_diary.receiver = request.user
# 로그인, 회원가입, 로그아웃 기능
def signup_view(request):
if request.method == "POST":
form = SignupForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
new_profile = Profile()
new_profile.user = user
new_profile.save()
return redirect('/')
else:
form = SignupForm()
return render(request, 'signup.html', {'form': form})
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request, request.POST)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(
request=request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
def logout_view(request):
logout(request)
return redirect('/')
def write(request):
user = request.user
profile = Profile.objects.get(user=user)
if request.method == 'GET':
return render(request, 'write.html')
elif request.method == 'POST':
new_diary = Diary()
new_diary.nickname = request.POST['nickname']
new_diary.profile = profile
new_diary.content = request.POST['content']
new_diary.title = request.POST['title']
if request.POST['location']:
new_diary.address = request.POST['location']
else:
pass
new_diary.save()
random_content = Diary.objects.order_by("?").first()
profile = Profile.objects.get(user=user)
random_content.receiver.add(profile)
return redirect('/')
def follow(request, user_pk, diary_pk):
user = request.user
unknown = User.objects.get(id=user_pk)
profile = Profile.objects.get(user=unknown)
profile.request.add(user)
profile.save()
return redirect('/detail/'+str(diary_pk))
def mypage(request):
user = request.user
profile = Profile.objects.get(user=user)
requests = profile.request.all()
# print('-'*100)
# print(request)
followers = profile.follower.all()
followings = profile.following.all()
ctx = {
'user': user,
'profile': profile,
'requests': requests,
'followers': followers,
'followings': followings
}
return render(request, 'mypage.html', ctx)
def accept(request, pk):
user = request.user
profile = Profile.objects.get(user=user)
unknown = User.objects.get(id=pk)
unknown_profile = Profile.objects.get(user=unknown)
profile.follower.add(unknown)
profile.request.remove(unknown)
profile.save()
unknown_profile.following.add(user)
unknown_profile.save()
return redirect('/mypage')
def reject(request, pk):
user = request.user
profile = Profile.objects.get(user=user)
unknown = User.objects.get(id=pk)
profile.request.remove(unknown)
profile.save()
return redirect('/mypage')
# others페이지 관리함수
def others(request):
user = request.user
profile = Profile.objects.get(user=user)
contents = Diary.objects.filter(receiver=profile).order_by('-date')
return render(request, 'others.html', {'contents': contents})
|
{"/sumda/views.py": ["/sumda/forms.py", "/sumda/models.py"], "/sumda/urls.py": ["/sumda/views.py"], "/sumda/forms.py": ["/sumda/models.py"]}
|
28,055,530
|
junankim18/sinchon
|
refs/heads/master
|
/sumda/models.py
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
class User(AbstractUser):
nickname = models.CharField(verbose_name='사용자 닉네임', max_length=50)
class Profile(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE)
follower = models.ManyToManyField(
User, related_name='follower', blank=True)
following = models.ManyToManyField(
User, related_name='following', blank=True)
request = models.ManyToManyField(
User, related_name='request', blank=True)
def __str__(self):
return self.user.nickname
class Diary(models.Model):
objects = models.Manager()
nickname = models.CharField(max_length=50)
profile = models.ForeignKey(
Profile, related_name='profile', on_delete=models.CASCADE, blank=True, null=True)
address = models.CharField(
verbose_name='주소', max_length=100, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
title = models.CharField(verbose_name='일기 제목',
max_length=100, blank=True, null=True)
content = models.TextField(blank=True, null=True)
receiver = models.ManyToManyField(
Profile, related_name='receiver', blank=True)
block = models.BooleanField(default=False)
def __str__(self):
return self.title
class Comment(models.Model):
objects = models.Manager()
comment = models.TextField(blank=True, null=True)
diary = models.ForeignKey(
Diary, related_name='diary', on_delete=models.CASCADE, blank=True, null=True)
nickname = models.CharField(max_length=50)
|
{"/sumda/views.py": ["/sumda/forms.py", "/sumda/models.py"], "/sumda/urls.py": ["/sumda/views.py"], "/sumda/forms.py": ["/sumda/models.py"]}
|
28,055,531
|
junankim18/sinchon
|
refs/heads/master
|
/sumda/forms.py
|
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import User, Comment
#회원가입
class SignupForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2','nickname']
#댓글
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['nickname', 'comment']
|
{"/sumda/views.py": ["/sumda/forms.py", "/sumda/models.py"], "/sumda/urls.py": ["/sumda/views.py"], "/sumda/forms.py": ["/sumda/models.py"]}
|
28,055,532
|
junankim18/sinchon
|
refs/heads/master
|
/sumda/urls.py
|
from django.urls import path, include
from .views import *
from . import views
app_name = 'sumda'
urlpatterns = [
path('', main, name='main'),
path('signup/', views.signup_view, name='signup'),
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
path('detail/<int:pk>', views.detail, name="detail"),
path('write', write, name='write'),
path('mypage', mypage, name='mypage'),
path('follow/<int:user_pk>/<int:diary_pk>', follow, name='follow'),
path('accept/<int:pk>', accept, name='accept'),
path('reject/<int:pk>', reject, name='reject'),
path('others/', views.others, name='others'),
]
|
{"/sumda/views.py": ["/sumda/forms.py", "/sumda/models.py"], "/sumda/urls.py": ["/sumda/views.py"], "/sumda/forms.py": ["/sumda/models.py"]}
|
28,117,742
|
KyleAllhusen/network-visualizer
|
refs/heads/main
|
/main.py
|
import json
import sys
import networkx as nx
import matplotlib.pyplot as plt
# make sure key exists in json file.
def check_key(key):
if key not in data_file:
print("no {0}. Enter a valid json file.".format(key))
exit(0)
# get file from command line arg
file = sys.argv[1]
# Initialize Graph
G = nx.Graph()
# Lists where values are stored from JSON
edges = []
heights = []
nodes = []
locations = []
with open(file, "r") as json_file:
assert file.endswith(".json")
data_file = json.load(json_file)
check_key("connections")
numEdges = len(data_file['connections'])
for i in range(0, numEdges):
edges.append(tuple(data_file['connections'][i]['nodes']))
check_key("heightsByEvent")
numHeights = len(data_file['heightsByEvent']['0'])
if numHeights <= 0:
print("File has no heights.")
exit(0)
for i in range(0, numHeights):
idx = str(i)
heights.append(data_file['heightsByEvent']['0'][idx])
for name in range(0, numHeights):
nodes.append(name)
# Create the locations where nodes will be placed.
x = numHeights * -1
for i in range(0, numHeights):
tup = (x, heights[i])
locations.append(tup)
if x < numHeights:
x = x + 1.0
else:
x = 0
# dictionary of node positions
pos = dict(zip(nodes, locations))
G.add_edges_from(edges)
fig, ax = plt.subplots()
nx.draw(G,
pos=pos,
ax=ax,
with_labels=True,
font_color="White",
node_color="Navy")
limits = plt.axis('on')
ax.tick_params(left=True, labelleft=True)
ax.grid()
plt.show()
|
{"/main.py": ["/parsecl.py", "/functions.py"], "/user_input.py": ["/main.py"]}
|
28,125,283
|
spence97/nasaaccess
|
refs/heads/master
|
/tethysapp-nasaaccess/tethysapp/nasaaccess/nasaaccess_r.py
|
import rpy2
def gldaspoly(watershed, DEM, start, end):
app_workspace = app.get_app_workspace()
|
{"/tethysapp-nasaaccess/tethysapp/nasaaccess/upload_file.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/config.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/model.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/config.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/views.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/forms.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/upload_file.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/app.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/forms.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/model.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/controllers.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/forms.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/upload_file.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/app.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/config.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/nasaaccess_r.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/nasaaccess_r.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/app.py"]}
|
28,125,284
|
spence97/nasaaccess
|
refs/heads/master
|
/tethysapp-nasaaccess/tethysapp/nasaaccess/model.py
|
from django.db import models
# Model for the Upload Shapefiles form
class Shapefiles(models.Model):
shapefile = models.FileField(upload_to='nasaaccess/shapefiles/')
# Model for the Upload DEM files form
class DEMfiles(models.Model):
DEMfile = models.FileField(upload_to='nasaaccess/DEMfiles/')
|
{"/tethysapp-nasaaccess/tethysapp/nasaaccess/upload_file.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/config.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/model.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/config.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/views.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/forms.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/upload_file.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/app.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/forms.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/model.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/controllers.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/forms.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/upload_file.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/app.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/config.py", "/tethysapp-nasaaccess/tethysapp/nasaaccess/nasaaccess_r.py"], "/tethysapp-nasaaccess/tethysapp/nasaaccess/nasaaccess_r.py": ["/tethysapp-nasaaccess/tethysapp/nasaaccess/app.py"]}
|
28,125,742
|
gelargew/tpa
|
refs/heads/main
|
/tes/migrations/0007_auto_20201013_1024.py
|
# Generated by Django 3.1.2 on 2020-10-13 03:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tes', '0006_auto_20201013_0952'),
]
operations = [
migrations.AddField(
model_name='person',
name='subtest1',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='person',
name='subtest2',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='person',
name='subtest3',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='person',
name='subtest4',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='question',
name='subtest',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='question',
name='ans',
field=models.CharField(default='a/b/c/d/e', max_length=50),
),
]
|
{"/tes/forms.py": ["/tes/models.py"], "/tes/views.py": ["/tes/models.py"], "/tes/admin.py": ["/tes/models.py"]}
|
28,125,743
|
gelargew/tpa
|
refs/heads/main
|
/tes/migrations/0005_question_choicee.py
|
# Generated by Django 3.1.2 on 2020-10-13 02:48
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('tes', '0004_person_nilai'),
]
operations = [
migrations.AddField(
model_name='question',
name='choiceE',
field=models.CharField(default=django.utils.timezone.now, max_length=200),
preserve_default=False,
),
]
|
{"/tes/forms.py": ["/tes/models.py"], "/tes/views.py": ["/tes/models.py"], "/tes/admin.py": ["/tes/models.py"]}
|
28,125,744
|
gelargew/tpa
|
refs/heads/main
|
/tes/migrations/0006_auto_20201013_0952.py
|
# Generated by Django 3.1.2 on 2020-10-13 02:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tes', '0005_question_choicee'),
]
operations = [
migrations.AlterField(
model_name='question',
name='ans',
field=models.CharField(default='a/b/c/d/e', max_length=200),
),
]
|
{"/tes/forms.py": ["/tes/models.py"], "/tes/views.py": ["/tes/models.py"], "/tes/admin.py": ["/tes/models.py"]}
|
28,125,745
|
gelargew/tpa
|
refs/heads/main
|
/tes/migrations/0003_auto_20201012_2235.py
|
# Generated by Django 3.1.2 on 2020-10-12 15:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tes', '0002_person'),
]
operations = [
migrations.RenameField(
model_name='question',
old_name='choice1',
new_name='choiceA',
),
migrations.RenameField(
model_name='question',
old_name='choice2',
new_name='choiceB',
),
migrations.RenameField(
model_name='question',
old_name='choice3',
new_name='choiceC',
),
migrations.RenameField(
model_name='question',
old_name='choice4',
new_name='choiceD',
),
]
|
{"/tes/forms.py": ["/tes/models.py"], "/tes/views.py": ["/tes/models.py"], "/tes/admin.py": ["/tes/models.py"]}
|
28,176,349
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/tests/test_ansible_taskrunner.py
|
#!/usr/bin/env python
# coding=utf-8
""" Unit tests for ansible taskrunner
"""
from __future__ import print_function, absolute_import
from click.testing import CliRunner
import os
from subprocess import PIPE, Popen
import sys
import unittest
import warnings
# Globals
__author__ = 'etejeda'
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root + '/ansible_taskrunner')
# Don't create .pyc files for non-modules
sys.dont_write_bytecode = True
import cli as cli_interface
class TestCli(unittest.TestCase):
def setUp(self):
self.cli = CliRunner()
def test_help(self):
""" Test whether script help will return. Basically check whether there are compile errors
:return: exit_code == 0
"""
self.assertEqual(self.cli.invoke(cli_interface.cli, ['--help']).exit_code, 0)
pass
def test_run_help(self):
""" Test whether script help will successfully execute. Basically check whether there are compile errors
:return: exit_code == 0
"""
self.assertEqual(self.cli.invoke(cli_interface.cli, ['run', '--help']).exit_code, 0)
pass
def test_run_foo_echo(self):
""" Test whether script 'run' subcommand will successfully echo subcommand. Basically check whether there are compile errors
:return: exit_code == 0
"""
self.assertEqual(self.cli.invoke(cli_interface.cli, ['run', '-f', 'foo', '---echo']).exit_code, 0)
pass
def test_run_make_hello(self):
""" Test whether script 'run' subcommand will successfully execute in make mode. Basically check whether there are compile errors
:return: exit_code == 0
"""
self.assertEqual(self.cli.invoke(cli_interface.cli, ['run', '-f', 'foo', '---make', 'hello']).exit_code, 0)
pass
def test_run_make_echo(self):
""" Test whether script 'run' subcommand will successfully echo subcommand in make mode. Basically check whether there are compile errors
:return: exit_code == 0
"""
self.assertEqual(self.cli.invoke(cli_interface.cli, ['run', '-f', 'foo', '---make', 'hello','---echo']).exit_code, 0)
pass
def test_direct_call(self):
proc = Popen(['python', 'ansible_taskrunner/cli.py', '--help'], stdout=PIPE)
stdout, stderr = proc.communicate()
self.assertTrue(stdout.startswith(b'Usage:'))
self.assertEquals(0, proc.returncode)
if __name__ == '__main__':
with warnings.catch_warnings(record=True):
unittest.main()
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,350
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/libs/proc_mgmt/__init__.py
|
import logging
import os
import subprocess
from subprocess import Popen, PIPE, STDOUT
import re
import sys
import threading
import time
# Account for script packaged as an exe via cx_freeze
if getattr(sys, 'frozen', False):
self_file_name = os.path.basename(sys.executable)
tasks_file_path = os.path.abspath(sys.executable)
else:
# Account for script packaged as zip app
self_file_name = os.path.basename(__file__)
_tasks_file_path = re.split('.tasks.', os.path.abspath(__file__))[0]
tasks_file_path = os.path.join(_tasks_file_path, 'tasks')
# Import third-party and custom modules
try:
from libs.formatting import Struct
except ImportError as e:
print('Error in %s ' % os.path.basename(self_file_name))
print('Failed to import at least one required module')
print('Error was %s' % e)
print('Please install/update the required modules:')
print('pip install -U -r requirements.txt')
sys.exit(1)
# Define how we handle different shell invocations
shell_invocation_mappings = {
'bash': '{src}',
'python': 'python -c """{src}"""',
'ruby': 'ruby < <(echo -e """{src}""")'
}
# Setup Logging
logger = logging.getLogger(__name__)
if '--debug run' in ' '.join(sys.argv):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
class Remote_CLIInvocation:
def __init__(self, settings, client):
self.settings = settings
self.ssh = client
def call(self, dirname, cmd, stdout_listen=False):
base_cmd = """
cd {};
""".format(dirname.replace('\\', '/'))
remote_cmd = base_cmd + cmd
if stdout_listen:
stdin, stdout, stderr = self.ssh.execute(remote_cmd, stream_stdout=stdout_listen)
exit_code = stdout.channel.recv_exit_status()
cli_result = {
'stdout' : [l.strip() for l in stdout],
'stderr' : [l.strip() for l in stderr],
'returncode': exit_code
}
return Struct(**cli_result)
else:
stdin, stdout, stderr = self.ssh.execute(remote_cmd)
exit_code = stdout.channel.recv_exit_status()
stdout = stdout.readlines() or "None"
stderr = stderr.readlines() or "None"
if exit_code == 0:
return [l.strip() for l in stdout]
else:
logger.error('Remote command failed with error {}: {}'.format(exit_code,stderr))
return False
class CLIInvocation:
def __init__(self):
self.proc = None
self.done = False
self.invocation = type('obj', (object,), {
'stdout': None,
'failed': False,
'returncode': 0
}
)
@staticmethod
def which(program):
"""
Returns the fully-qualified path to the specified binary
"""
def is_exe(filepath):
if sys.platform == 'win32':
filepath = filepath.replace('\\', '/')
for exe in [filepath, filepath + '.exe']:
if all([os.path.isfile(exe), os.access(exe, os.X_OK)]):
return True
else:
return os.path.isfile(filepath) and os.access(filepath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def call(self, cmd, exe='bash', debug_enabled=False, suppress_output=False):
executable = self.which(exe)
if debug_enabled:
process_invocation = [executable,'-x','-c', cmd]
else:
process_invocation = [executable, '-c', cmd]
def s():
try:
if sys.version_info[0] >= 3:
with Popen(process_invocation, stdout=PIPE, stderr=STDOUT, bufsize=1, universal_newlines=True) as self.proc:
if not suppress_output:
for line in self.proc.stdout:
sys.stdout.write(line) # process line here
if self.proc.returncode != 0:
self.invocation.failed = True
self.invocation.returncode = p.returncode
self.invocation.stdout = 'Encountered error code {errcode} in the specified command {args}'.format(
errcode=p.returncode, args=p.args)
self.done = True
self.done = True
self.invocation.returncode = self.proc.returncode
else:
# Invoke process
self.proc = Popen(
process_invocation,
stdout=PIPE,
stderr=STDOUT)
# Poll for new output until finished
while True:
nextline = self.proc.stdout.readline()
if nextline == '' and self.proc.poll() is not None:
break
if not suppress_output:
sys.stdout.write(nextline)
sys.stdout.flush()
self.done = True
self.invocation.returncode = self.proc.returncode
# ['__class__', '__del__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_child_created', '_close_fds', '_communicate', '_communicate_with_poll', '_communicate_with_select', '_execute_child', '_get_handles', '_handle_exitstatus', '_internal_poll', '_set_cloexec_flag', '_translate_newlines', 'communicate', 'kill', 'pid', 'pipe_cloexec', 'poll', 'returncode', 'send_signal', 'stderr', 'stdin', 'stdout', 'terminate', 'universal_newlines', 'wait']
except Exception:
self.done = True
try:
if sys.version_info[0] >= 3:
t = threading.Thread(target=s, daemon=True)
else:
t = threading.Thread(target=s)
t.start()
except Exception:
pass
try:
while not self.done:
time.sleep(0.1)
return self.invocation
except KeyboardInterrupt:
print("KeyboardInterrupt")
try:
self.proc.terminate()
except Exception:
pass
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,351
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/libs/yamlr/__init__.py
|
from functools import reduce
class YamlReader:
def __init__(self):
pass
def deep_get(self, data_input, keys, default=None):
"""Recursively retrieve values from a dictionary object"""
result = ''
if isinstance(data_input, dict):
result = reduce(lambda d, key: d.get(key, default) if isinstance(
d, dict) else default, keys.split('.'), data_input)
return(result)
def get(self, yaml_input, dict_path, default_data=''):
"""Interpret wildcard paths for retrieving values from a dictionary object"""
try:
ks = dict_path.split('.*.')
if len(ks) > 1:
path_string = ks[0]
ds = self.deep_get(yaml_input, path_string)
for d in ds:
path_string + '.{dd}.{dv}'.format(dd=d, dv=ks[1])
data = self.deep_get(yaml_input, path_string)
return data
else:
data = self.deep_get(yaml_input, dict_path)
if not isinstance(data, dict):
data = {'data': data}
return data
except Exception as e:
raise(e)
else:
return default_data
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,352
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/__init__.py
|
# -*- coding: utf-8 -*-
"""Top-level package for ansible-taskrunner."""
__author__ = """Engelbert Tejeda"""
__email__ = 'berttejeda@gmail.com'
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,353
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/libs/providers/ansible.py
|
# Imports
import logging
import json
import os
from os import fdopen, remove
import re
import uuid
import sys
import time
from tempfile import mkstemp
provider_name = 'ansible'
# Setup Logging
logger = logging.getLogger(__name__)
if '--debug run' in ' '.join(sys.argv):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
if getattr(sys, 'frozen', False):
# frozen
self_file_name = os.path.basename(sys.executable)
else:
self_file_name = os.path.basename(__file__)
# Import third-party and custom modules
try:
import click
from libs.formatting import ansi_colors, Struct
from libs.proc_mgmt import shell_invocation_mappings
from libs.proc_mgmt import CLIInvocation
except ImportError as e:
print('Error in %s ' % os.path.basename(self_file_name))
print('Failed to import at least one required module')
print('Error was %s' % e)
print('Please install/update the required modules:')
print('pip install -U -r requirements.txt')
sys.exit(1)
class ProviderCLI:
def __init__(self, parameter_set=None, vars_input=None):
if vars_input is None:
vars_input = {}
self.vars = vars_input
self.parameter_set = parameter_set
self.logger = logger
pass
@staticmethod
def options(func):
"""Add provider-specific click options"""
option = click.option('---debug', type=str, help='Start task run with ansible in debug mode',
default=False, required=False)
func = option(func)
option = click.option('---inventory', help='Specify inventory path if not using embedded inventory',
required=False)
func = option(func)
option = click.option('---inventory-tmp-dir', help='Override path where we create embedded temporary inventory',
required=False)
func = option(func)
return func
def invoke_bastion_mode(self, bastion_settings, invocation, remote_command, kwargs):
"""Execute the underlying subprocess via a bastion host"""
logger.info('Engage Bastion Mode')
paramset = invocation.get('param_set')
bastion = Struct(**bastion_settings)
logger.info('Checking for SFTP config file %s' % bastion.config_file)
if os.path.exists(bastion.config_file):
logger.info('Reading %s' % bastion.config_file)
try:
# Read the Sublime Text 3-compatible sftp config file
file_contents = open(bastion.config_file).readlines()
# Ignore comments
file_contents_no_comments = [l.strip() for l in file_contents if not l.strip().startswith('/') and l.strip()]
# Account for last line possibly ending in ','
penultimate_line = file_contents_no_comments[-2]
if penultimate_line.endswith(','):
file_contents_no_comments = [penultimate_line.strip(',') if l==penultimate_line else l for l in file_contents_no_comments]
file_contents_no_comments = '\n'.join(file_contents_no_comments)
settings = Struct(**json.loads(file_contents_no_comments))
except Exception as e:
logger.error('I trouble reading {c}, error was "{err}"'.format(
c=bastion.config_file,
err=e)
)
sys.exit(1)
else:
# If no sftp config is found,
# we should check if a bastion-host
# was specified
bastion_host = kwargs.get('_bastion_host')
if bastion_host:
from string import Template
try:
from libs.bastion_mode import init_bastion_settings
from libs.help import SAMPLE_SFTP_CONFIG
except ImportError as e:
print('Error in %s ' % os.path.basename(self_file_name))
print('Failed to import at least one required module')
print('Error was %s' % e)
print('Please install/update the required modules:')
print('pip install -U -r requirements.txt')
sys.exit(1)
settings_vars = init_bastion_settings(kwargs)
in_memory_sftp_settings = Template(SAMPLE_SFTP_CONFIG).safe_substitute(**settings_vars)
settings = Struct(**json.loads(in_memory_sftp_settings))
else:
logger.error("Could not find %s, and no bastion-host was specified. Please run 'tasks init --help'" % bastion.config_file)
sys.exit(1)
# Import third-party and custom modules
try:
from libs.proc_mgmt import Remote_CLIInvocation
from libs.sshutil.client import SSHUtilClient
except ImportError as e:
print('Error in %s ' % os.path.basename(self_file_name))
print('Failed to import at least one required module')
print('Error was %s' % e)
print('Please install/update the required modules:')
print('pip install -U -r requirements.txt')
sys.exit(1)
ssh_client = SSHUtilClient(settings)
sftp_sync = ssh_client.sync()
remote_sub_process = Remote_CLIInvocation(settings, ssh_client)
local_dir = os.getcwd().replace('\\', '/')
local_dir_name = os.path.basename(os.getcwd().replace('\\', '/'))
remote_dir = settings.remote_path
logger.info('Checking remote path %s' % remote_dir)
cmd = 'echo $(test -d {0} && echo 1 || echo 0),$(cd {0} 2>/dev/null && git status 1> /dev/null 2> /dev/null && echo 1 || echo 0)'.format(remote_dir)
# Check whether the remote path exists and is a git repo
rmc = remote_sub_process.call(remote_dir, cmd) or ['0']
rms = sum([int(n) for n in ''.join(rmc).split(',')])
rem_exists = True if rms > 0 else False
loc_is_git = True if os.path.exists('.git') else False
rem_is_git = True if rms == 2 else False
if rem_is_git:
logger.info('OK, remote path exists and is a git repo - %s' % remote_dir)
elif rem_exists:
logger.info('OK, remote path exists - %s' % remote_dir)
else:
cmd = 'mkdir -p %s' % remote_dir
mkdir_result = remote_sub_process.call('/', cmd)
if mkdir_result:
logger.info("Performing initial sync to %s ..." % remote_dir)
sftp_sync.to_remote(os.getcwd(), '%s/..' % remote_dir)
rem_exists = True
else:
logger.error('Unable to create remote path!')
sys.exit(1)
logger.info('Checking for locally changed files ...')
if loc_is_git:
# List modified and untracked files
changed_cmd = '''git diff-index HEAD --name-status'''
changed_files = [f.strip().split('\t')[1] for f in os.popen(changed_cmd).readlines() if not f.startswith('D\t')]
untracked_cmd = '''git ls-files --others --exclude-standard'''
untracked_files = [f.strip() for f in os.popen(untracked_cmd).readlines()]
local_changed = changed_files + untracked_files
else:
# If local path is not a git repo then
# we'll only sync files in the current working directory
# that have changed within the last 5 minutes
_dir = os.getcwd()
exclusions = ['sftp-config.json']
local_changed = list(fle for rt, _, f in os.walk(_dir) for fle in f if time.time() - os.stat(os.path.join(rt, fle)).st_mtime < 300 and f not in exclusions)
logger.info('Checking for remotely changed files ...')
no_clobber = settings.get('at_no_clobber')
if rem_is_git:
remote_changed_cmd = '''{} | awk '$1 != "D" {{print $2}}' && {}'''.format(changed_cmd, untracked_cmd)
remote_changed = remote_sub_process.call(remote_dir, cmd)
if remote_changed:
if no_clobber:
to_sync = list(set(local_changed) - set(remote_changed))
else:
to_sync = list(set(local_changed))
else:
logger.error('There was a problem checking for remotely changed files')
sys.exit(1)
else:
to_sync = list(set(local_changed))
if len(to_sync) > 0:
logger.info("Performing sync to %s ..." % remote_dir)
for path in to_sync:
dirname = os.path.dirname(path)
filename = os.path.basename(path).strip()
_file_path = os.path.join(dirname, filename)
file_path = _file_path.replace('\\','/')
_remote_path = os.path.join(remote_dir, file_path)
remote_path = os.path.normpath(_remote_path).replace('\\','/')
logger.debug('Syncing {} to remote {}'.format(file_path, remote_path))
sftp_sync.to_remote(file_path, remote_path)
remote_command_result = remote_sub_process.call(remote_dir, remote_command, stdout_listen=True)
if remote_command_result.returncode > 0:
logger.error('Remote command failed with: %s' % ' '.join(remote_command_result.stderr))
sys.exit(remote_command_result.returncode)
else:
return remote_command_result
def invocation(self,
args=None,
bastion_settings={},
bash_functions=[],
cli_vars='',
debug=False,
default_vars={},
invocation={},
kwargs={},
list_vars=[],
paramset_var=None,
prefix='',
raw_args='',
string_vars=[],
suppress_output=False,
yaml_input_file=None,
yaml_vars={}):
"""Invoke commands according to provider"""
logger.debug('Ansible Command Provider')
ansible_playbook_command = default_vars.get(
'ansible_playbook_command', 'ansible-playbook')
# Embedded inventory logic
embedded_inventory = False
# Employ an exit trap if we're using bastion mode
trap = ''
# Where to create the temporary inventory (if applicable)
inventory_dir = kwargs.get('_inventory_tmp_dir') or yaml_vars.get('inventory_dir')
inventory_input = kwargs.get('_inventory')
embedded_inventory_string = yaml_vars.get('inventory')
if not inventory_input and not embedded_inventory_string:
logger.error(
"Playbook does not contain an inventory declaration and no inventory was specified. Seek --help")
sys.exit(1)
elif inventory_input:
ans_inv_fp = inventory_input
ans_inv_fso_desc = None
logger.debug("Using specified inventory file %s" % ans_inv_fp)
if bastion_settings.get('enabled'):
if not debug:
trap = 'trap "rm -f %s" EXIT' % ans_inv_fp
else:
if bastion_settings.get('enabled'):
inventory_dir = '/tmp' if not inventory_dir else inventory_dir
ans_inv_fp = '{}/ansible.inventory.{}.tmp.ini'.format(inventory_dir, uuid.uuid4())
ans_inv_fso_desc = None
if not debug:
trap = 'trap "rm -f %s" EXIT' % ans_inv_fp
else:
ans_inv_fso_desc, ans_inv_fp = mkstemp(prefix='ansible-inventory', suffix='.tmp.ini', dir=inventory_dir)
logger.debug("No external inventory specified")
logger.debug("Created temporary inventory file %s (normally deleted after run)" % ans_inv_fp)
inventory_input = embedded_inventory_string
embedded_inventory = True
ansible_extra_options = [
'-e {k}="{v}"'.format(k=key, v=value) for key, value in kwargs.items() if value]
# Append our default values to the set of ansible extra options
ansible_extra_options = ansible_extra_options + [
'-e {k}="{v}"'.format(k=key, v=value) for key, value in default_vars.items() if value]
# Append the parameter sets var to the set of ansible extra options
ansible_extra_options.append('-e %s' % paramset_var)
# Build command string
if ans_inv_fso_desc or bastion_settings.get('enabled'):
inventory_command = '''
{tr}
if [[ ($inventory) && ( '{emb}' == 'True') ]];then
echo -e """{ins}""" | while read line;do
eval "echo -e ${{line}}" >> "{inf}"
done
fi
'''.format(
tr=trap,
emb=embedded_inventory,
ins=inventory_input,
inf=ans_inv_fp,
)
else:
inventory_command = ''
pre_commands = '''{anc}
{clv}
{dsv}
{dlv}
{bfn}
{inc}'''.format(
anc=ansi_colors.strip(),
dlv='\n'.join(list_vars),
dsv='\n'.join(string_vars),
clv=cli_vars.strip(),
bfn='\n'.join(bash_functions),
inc=inventory_command,
deb=debug
)
ansible_command = '''
{apc} ${{__ansible_extra_options}} -i {inf} {opt} {arg} {raw} {ply}
'''.format(
apc=ansible_playbook_command,
inf=ans_inv_fp,
opt=' '.join(ansible_extra_options),
ply=yaml_input_file,
arg=args,
raw=raw_args
)
command = pre_commands + ansible_command
# Command invocation
# Bastion host logic
result = None
if prefix == 'echo':
logger.info("ECHO MODE ON")
if debug:
print(pre_commands)
print(ansible_command)
else:
print(inventory_command)
print(ansible_command)
else:
if bastion_settings.get('enabled'):
result = self.invoke_bastion_mode(bastion_settings, invocation, command, kwargs)
else:
sub_process = CLIInvocation()
result = sub_process.call(command, debug_enabled=debug, suppress_output=suppress_output)
# Debugging
if debug:
ansible_command_file_descriptor, ansible_command_file_path = mkstemp(prefix='ansible-command',
suffix='.tmp.sh')
logger.debug('Ansible command file can be found here: %s' %
ansible_command_file_path)
logger.debug('Ansible inventory file can be found here: %s' %
ans_inv_fp)
with fdopen(ansible_command_file_descriptor, "w") as f:
f.write(command)
else:
if ans_inv_fso_desc:
os.close(ans_inv_fso_desc)
remove(ans_inv_fp)
if result:
sys.exit(result.returncode)
else:
sys.exit(0)
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,354
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/libs/superduperconfig/__init__.py
|
import logging
import os
import sys
from collections import OrderedDict
import yaml
# Setup Logging
logger = logging.getLogger(__name__)
if '--debug run' in ' '.join(sys.argv):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
class SuperDuperConfig():
def __init__(self, prog_name):
self.program_name = prog_name
self.logger = logger
pass
def ordered_load(self, stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return yaml.load(stream, OrderedLoader)
def load_config(self, config_file, req_keys=[], failfast=False, data_key=None, debug=False):
""" Load config file
"""
config_path_strings = [
os.path.realpath(os.path.expanduser(
os.path.join('~', '.%s' % self.program_name))),
'.', '/etc/%s' % self.program_name
]
config_paths = [os.path.join(p, config_file)
for p in config_path_strings]
config_found = False
config_is_valid = False
for config_path in config_paths:
config_exists = os.path.exists(config_path)
if config_exists:
config_found = True
try:
with open(config_path, 'r') as ymlfile:
# Preserve dictionary order for python 2
# https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
if sys.version_info[0] < 3:
cfg = self.ordered_load(ymlfile, yaml.Loader)
else:
cfg = yaml.load(ymlfile, yaml.Loader)
config_dict = cfg[data_key] if data_key is not None else cfg
config_is_valid = all([m[m.keys()[0]].get(k)
for k in req_keys for m in config_dict])
self.logger.debug(
"Found input file - {cf}".format(cf=config_path))
if not config_is_valid:
logger.warning(
"""At least one required key was not defined in your input file: {cf}.""".format(
cf=config_path)
)
self.logger.warning(
"Review the available documentation or consult --help")
config_file = config_path
break
except Exception as e:
self.logger.warning(
"I encountered a problem reading your input file: {cp}, error was {err}".format(
cp=config_path, err=str(e))
)
if not config_found:
if failfast:
self.logger.error("Could not find %s. Aborting." % config_file)
sys.exit(1)
else:
self.logger.debug(
"Could not find %s, not loading values" % config_file)
if config_found and config_is_valid:
return config_dict
else:
if failfast:
self.logger.error(
"Config %s is invalid. Aborting." % config_file)
sys.exit(1)
else:
return {}
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,355
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/libs/click_extras/__init__.py
|
# Imports
import logging
import os
import re
import sys
from string import Template
# Setup Logging
logger = logging.getLogger(__name__)
if '--debug run' in ' '.join(sys.argv):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
if getattr(sys, 'frozen', False):
# frozen
self_file_name = os.path.basename(sys.executable)
else:
self_file_name = os.path.basename(__file__)
# Import third-party and custom modules
try:
import click
except ImportError as e:
print('Error in %s ' % os.path.basename(self_file_name))
print('Failed to import at least one required module')
print('Error was %s' % e)
print('Please install/update the required modules:')
print('pip install -U -r requirements.txt')
sys.exit(1)
class ExtendedEpilog(click.Group):
def format_epilog(self, ctx, formatter):
"""Format click epilog to honor newline characters"""
if self.epilog:
formatter.write_paragraph()
for line in self.epilog.split('\n'):
formatter.write_text(line)
class ExtendedHelp(click.Command):
def colorize(self, formatter, color, string):
if color == 'green':
formatter.write_text('%s' % click.style(string, fg='bright_green'))
elif color == 'magenta':
formatter.write_text('%s' % click.style(string, fg='bright_magenta'))
elif color == 'red':
formatter.write_text('%s' % click.style(string, fg='bright_red'))
elif color == 'yellow':
formatter.write_text('%s' % click.style(string, fg='bright_yellow'))
else:
formatter.write_text(string)
def format_help(self, ctx, formatter):
"""Format click help to honor newline characters"""
if self.help:
formatter.write_paragraph()
for line in self.help.split('\n'):
formatter.write_text(line)
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
opts.append(rv)
if opts:
with formatter.section('Options'):
formatter.write_dl(opts)
if self.epilog:
formatter.write_paragraph()
for line in self.epilog.split('\n'):
if line:
if line.startswith('-'):
self.colorize(formatter, 'magenta', line)
else:
self.colorize(formatter, 'yellow', line)
else:
formatter.write_text(line)
# Allow for mutually-exlusive click options
class NotRequiredIf(click.Option):
def __init__(self, *args, **kwargs):
self.not_required_if = kwargs.pop('not_required_if')
assert self.not_required_if, "'not_required_if' parameter required"
kwargs['help'] = (kwargs.get('help', '') +
' NOTE: This argument is mutually exclusive with %s' %
self.not_required_if
).strip()
super(NotRequiredIf, self).__init__(*args, **kwargs)
def handle_parse_result(self, ctx, opts, args):
we_are_present = self.name in opts
other_present = self.not_required_if in opts
if other_present:
if we_are_present:
if self.name == self.not_required_if:
logger.error("Option order error: `%s`" % self.name)
logger.error("Make sure you call this option BEFORE any mutually-exlusive options referencing it")
logger.error("Check your tasks manifest")
sys.exit(1)
else:
logger.error(
"Illegal usage: `%s` is mutually exclusive with `%s`" % (
self.name, self.not_required_if))
sys.exit(1)
else:
self.prompt = None
return super(NotRequiredIf, self).handle_parse_result(
ctx, opts, args)
class ExtendCLI():
def __init__(self, parameter_set=None, vars_input={}, help_msg_map={}):
self.vars = vars_input
self.help_msg_map = help_msg_map
self.parameter_set = parameter_set
self.logger = logger
# Populate list of available variables for use in internal string Templating
self.sys_platform = sys.platform
self.available_vars = vars(self)
self.available_vars = dict([(v, self.available_vars[v]) for v in self.available_vars.keys() if not type(self.available_vars[v]) == dict])
pass
def process_options(self, parameters, func, is_required=False):
"""
Read dictionary of parameters and translate to click options
"""
# Account for parameter sets
vanilla_parameters = dict(
[(k, v) for k, v in parameters.items() if not isinstance(parameters[k], dict)])
if self.parameter_set:
existing_parameter_sets = dict(
[(k, v) for k, v in parameters.items() if isinstance(parameters[k], dict)])
# Exclude parameter sets we have not activated
excluded_parameter_sets = set(existing_parameter_sets) - set(self.parameter_set)
for es in excluded_parameter_sets:
parameters.pop(es)
# Build the options dictionary
for ps in self.parameter_set:
_parameters = parameters.get(ps, {})
if _parameters:
# Remove the parameter set parent key
parameters.pop(ps)
# Populate the values from the parameter set
parameters.update(_parameters)
else:
parameters = vanilla_parameters
# Variables used in logic for click's variadic arguments (nargs=*)
numargs = 1
nargs_ul_is_set = False
nargs_ul_count = 0
nargs_ul_count_max = 1
prompt_if_missing = False
secure_input = False
option_type = None
value_from_env = None
for cli_option, value in parameters.items():
cli_option = Template(cli_option).safe_substitute(**self.available_vars)
if isinstance(value, list):
value = [Template(v).safe_substitute(**self.available_vars) if isinstance(v, str) else v for v in value if isinstance(v, (str, int))]
elif isinstance(value, str):
value = Template(value).safe_substitute(**self.available_vars)
else:
logger.error('Skipping unsupported value type %s' % s)
continue
opt_option = None
opt_option_value = None
cli_option_is_me = False
if ' or ' in cli_option:
cli_option_l = cli_option.split(' or ')
cli_option = cli_option_l[0]
opt_option = cli_option_l[1]
opt_option_value = parameters.get(opt_option, '')
if not opt_option_value:
logger.debug('Skipping mutually exclusive option %s due to possible broken association' % opt_option)
continue
#If a given option is mutually exclusive with another,
#then whether or not it is required depends on the
#command-line invocation relating
# to its mutually exclusive partners
cli_option_is_me = any(['or %s' % cli_option in o for o,v in parameters.items()])
cli_option_me_pattern = re.compile(cli_option)
cli_option_is_called = any([cli_option_me_pattern.match(a) for a in sys.argv])
cli_option_other = []
for o,v in parameters.items():
if 'or %s' % cli_option in o:
cli_option_other.append(o.split(' or ')[0])
len_cli_option_other = len(cli_option_other)
cli_option_other = '|'.join(cli_option_other)
cli_option_other_pattern = re.compile(cli_option_other)
cli_option_other_matches = [cli_option_other_pattern.match(a) for a in sys.argv if cli_option_other_pattern.match(a)]
cli_option_other_is_called = any(cli_option_other_matches) and len(cli_option_other_matches) == len_cli_option_other
# Check for option with variadic arguments (nargs=*)
# There can only be one!
# Also, make sure we're not treating click.Choice types
if isinstance(value, list) and '|choice' not in cli_option:
if len(value) == 1:
nargs_ul_is_set = True
nargs_ul_count += 1
value = str(value[0])
numargs = -1
elif len(value) > 1:
if isinstance(value[1], int):
numargs = value[1] # e.g. [myvalue,2] would mean the option for myvalue requires 2 args
value = str(value[0])
# Account for click.Choice types
elif isinstance(value, list):
option_type = 'choice'
if self.help_msg_map.get(cli_option):
option_help = self.help_msg_map[cli_option]
else:
option_help = value
if '|' in cli_option:
option_strings = cli_option.split('|')
first_option = option_strings[0].strip()
second_option = option_strings[1].strip()
if len(option_strings) > 2:
option_tags = [o.strip() for o in option_strings[2:]]
if 'prompt' in option_tags:
prompt_if_missing = True
secure_input = False
if 'sprompt' in option_tags:
prompt_if_missing = True
secure_input = True
if 'env' in option_tags:
value_from_env = value
numargs = 1 if numargs < 1 else numargs
if opt_option:
if option_type == 'choice':
option = click.option(first_option, second_option,
type=click.Choice(value), help=option_help, cls=NotRequiredIf,
prompt=prompt_if_missing, hide_input=secure_input, not_required_if=opt_option_value,
envvar=value_from_env)
else:
option = click.option(first_option, second_option, value,
type=str, nargs=numargs, help=option_help, cls=NotRequiredIf,
prompt=prompt_if_missing, hide_input=secure_input, not_required_if=opt_option_value,
envvar=value_from_env)
else:
if cli_option_is_me and cli_option_other_is_called:
_is_required = False
else:
_is_required = is_required
if option_type == 'choice':
option = click.option(first_option, second_option,
type=click.Choice(value), help=option_help,
prompt=prompt_if_missing, hide_input=secure_input, required=_is_required,
envvar=value_from_env)
else:
option = click.option(first_option, second_option,
value, type=str, nargs=numargs, help=option_help,
prompt=prompt_if_missing, hide_input=secure_input, required=_is_required,
envvar=value_from_env)
else:
if nargs_ul_is_set and \
not nargs_ul_count > nargs_ul_count_max:
option = click.argument(
cli_option, value, help=option_help,
nargs=numargs, prompt=prompt_if_missing, hide_input=secure_input, required=is_required,
envvar=value_from_env)
else:
numargs = 1 if numargs < 1 else numargs
if opt_option:
option = click.option(
cli_option, value, cls=NotRequiredIf,
is_flag=True, default=False,
help=option_help, not_required_if=opt_option_value,
envvar=value_from_env)
else:
if cli_option_is_me and cli_option_other_is_called:
_is_required = False
else:
_is_required = is_required
option = click.option(
cli_option, value, is_flag=True,
default=False, help=option_help,
required=_is_required, envvar=value_from_env)
try:
func = option(func)
except Exception as e:
logger.error('I had a problem parsing your parameters, error was %s' % e)
continue
option_type = None
prompt_if_missing = False
secure_input = False
value_from_env = None
nargs_ul_is_set = False
numargs = 1
return func
def bastion_mode(self, func):
"""
Explicity define command-line options for bastion mode operation
"""
option = click.option('---bastion-mode',
is_flag=True,
help='Force execution of commands via a bastion host')
func = option(func)
# Determine if bastion host is a required parameter
if len(sys.argv) > 0 and sys.argv[0] == 'init':
bastion_host_required = True if sys.argv[0] == 'init' else False
elif len(sys.argv) > 1:
bastion_host_required = True if sys.argv[1] == 'init' else False
else:
bastion_host_required = False
# Determine if bastion mode is forced
force_bastion_mode = True if '---bastion-mode' in sys.argv else False
if sys.platform in ['win32', 'cygwin'] or force_bastion_mode:
option = click.option('---bastion-host','-h',
help='Specify bastion host',
required=bastion_host_required)
func = option(func)
option = click.option('---bastion-host-port','-p',
help='Specify bastion host port')
func = option(func)
option = click.option('---bastion-user','-u',
help='Override default username')
func = option(func)
option = click.option('---bastion-remote-path','-r',
help='Specify remote workspace')
func = option(func)
option = click.option('---bastion-ssh-key-file','-k',
help='Override default ssh key file')
func = option(func)
return func
def options(self, func):
"""
Read dictionary of parameters, append these
as additional options to incoming click function
"""
required_parameters = self.vars.get('required_parameters', {})
if not required_parameters:
required_parameters = {}
else:
param_list = list(required_parameters.items())
# Filter out any None/Null values
# Accounting for mutually exclusive options
for param in param_list:
if param[0] != 'or' and param[1] is None:
logger.debug("Removing invalid option key '%s'" % param[0])
required_parameters.pop(param[0])
extended_cli_func_required = self.process_options(
required_parameters, func, is_required=True)
optional_parameters = self.vars.get('optional_parameters', {})
if not optional_parameters:
optional_parameters = {}
else:
param_list = list(optional_parameters.items())
# Filter out any None values
# Accounting for mutually exclusive options
for param in param_list:
if param[0] != 'or' and param[1] is None:
logger.debug("Removing invalid option key '%s'" % param[0])
optional_parameters.pop(param[0])
extended_cli_func = self.process_options(
optional_parameters, extended_cli_func_required)
return extended_cli_func
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,176,356
|
berttejeda/ansible-taskrunner
|
refs/heads/develop
|
/ansible_taskrunner/cli.py
|
# -*- coding: utf-8 -*-
# Import builtins
from __future__ import print_function
from collections import OrderedDict
import getpass
import logging
import logging.handlers
import os
import re
import sys
from string import Template
# OS Detection
is_windows = True if sys.platform in ['win32', 'cygwin'] else False
is_darwin = True if sys.platform in ['darwin'] else False
# Account for script packaged as an exe via cx_freeze
if getattr(sys, 'frozen', False):
# frozen
self_file_name = script_name = os.path.basename(sys.executable)
project_root = os.path.dirname(os.path.abspath(sys.executable))
else:
# unfrozen
self_file_name = os.path.basename(__file__)
if self_file_name == '__main__.py':
script_name = os.path.dirname(__file__)
else:
script_name = self_file_name
project_root = os.path.dirname(os.path.abspath(__file__))
# Modify our sys path to include the script's location
sys.path.insert(0, project_root)
# Make the zipapp work for python2/python3
py_path = 'py3' if sys.version_info[0] >= 3 else 'py2'
sys.path.insert(0, os.path.join(project_root, 'libs', py_path))
# set Windows console in VT mode
if is_windows:
try:
kernel32 = __import__("ctypes").windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
del kernel32
except Exception:
pass
# Import third-party and custom modules
try:
import click
from libs.cliutil import get_invocation
from libs.errorhandler import catchException
from libs.errorhandler import ERR_ARGS_TASKF_OVERRIDE
from libs.formatting import logging_format
from libs.bastion_mode import init_bastion_settings
from libs.help import SAMPLE_CONFIG
from libs.help import SAMPLE_TASKS_MANIFEST
from libs.help import SAMPLE_SFTP_CONFIG
from libs.logger import init_logger
from libs.superduperconfig import SuperDuperConfig
from libs.click_extras import ExtendedEpilog
from libs.click_extras import ExtendedHelp
from libs.click_extras import ExtendCLI
from libs.proc_mgmt import shell_invocation_mappings
from libs.proc_mgmt import CLIInvocation
from libs.yamlr import YamlReader
# TODO
# Employ language/regional options
# from libs.language import get_strings
except ImportError as e:
print('Error in %s ' % os.path.basename(self_file_name))
print('Failed to import at least one required module')
print('Error was %s' % e)
print('Please install/update the required modules:')
print('pip install -U -r requirements.txt')
sys.exit(1)
# Cover My A$$
_cma = """
CMA:
This software is made available by the author in the hope
that it will be useful, but without any warranty.
The author is not liable for any consequence related to the
use of the provided application.
"""
_doc = """
Ansible Taskrunner - ansible-playbook wrapper
- YAML-abstracted python click cli options
- Utilizes a specially-formatted ansible-playbook (Taskfile.yaml)
to extend the ansible playbook command via
the python click module
"""
# Private variables
__author__ = 'etejeda'
__version__ = '1.4.2'
__program_name__ = 'tasks'
# Logging
logger = init_logger()
# We'll pass this down to the run invocation
global exe_path
global cli_args
global cli_args_short
global local_username
global parameter_sets
global sys_platform
global tf_path
cli_invocation = get_invocation(script_name)
try:
local_username = getpass.getuser()
except Exception:
local_username = os.environ.get('USERNAME') or os.environ.get('USER')
param_set = cli_invocation['param_set']
raw_args = cli_invocation['raw_args']
tasks_file = cli_invocation.get('tasks_file_override') or cli_invocation['tasks_file']
tasks_file_override = cli_invocation['tasks_file_override']
# Replace the commandline invocation
if __name__ in ['ansible_taskrunner.cli', '__main__']:
sys.argv = cli_invocation['cli']
# System Platform
sys_platform = sys.platform
exe_path = os.path.normpath(self_file_name)
exe_path = re.sub('.__main__.py','', exe_path)
# Parameter set var (if it has been specified)
paramset_var = 'parameter_sets="%s"' % (
','.join(param_set) if param_set else 'False')
parameter_sets = paramset_var
# Path to specified Taskfile
tf_path = os.path.normpath(os.path.expanduser(tasks_file))
# Instantiate YAML Reader Class
yamlr = YamlReader()
# Instantiate the cli invocation class
sub_process = CLIInvocation()
# Load Tasks Manifest
yaml_input_file = tasks_file
# Initialize Config Module
superconf = SuperDuperConfig(__program_name__)
# Configuration Files
config_file = 'config.yaml'
sftp_config_file = 'sftp-config.json'
config = superconf.load_config(config_file)
help_max_content_width = yamlr.deep_get(config, 'help.max_content_width', 200)
logging_maxBytes = yamlr.deep_get(config, 'logging.maxBytes', 10000000)
logging_backupCount = yamlr.deep_get(config, 'logging.backupCount', 5)
__debug = yamlr.deep_get(config, 'logging.debug', False)
verbose = yamlr.deep_get(config, 'logging.verbose', 0)
suppress_output = yamlr.deep_get(config, 'logging.silent', 0)
log_file = yamlr.deep_get(config, 'logging.log_file', None)
path_string = yamlr.deep_get(config, 'taskfile.path_string', 'vars')
if os.path.exists(yaml_input_file):
yaml_data = superconf.load_config(yaml_input_file, data_key=0)
else:
logger.warning(
"Couln't find %s or any other Tasks Manifest" % yaml_input_file
)
yaml_data = {}
# Extend CLI Options as per Tasks Manifest
yaml_vars = yamlr.get(yaml_data, path_string)
# cli_args
_sys_args = [a for a in sys.argv if a != '--help']
cli_args = ' '.join(_sys_args)
cli_args_short = ' '.join(_sys_args[1:])
# Populate list of available variables for use in internal string Templating
available_vars = dict([(v, globals()[v]) for v in globals().keys() if not v.startswith('_')])
# Create a dictionary object holding option help messages
option_help_messages = {}
if os.path.exists(tf_path):
string_pattern = re.compile('(.*-.*)##(.*)')
for line in open(tf_path).readlines():
match = string_pattern.match(line)
if match:
opt = match.groups()[0].strip().split(':')[0]
oph = match.groups()[1].strip()
option_help_messages[opt] = Template(oph).safe_substitute(**available_vars)
# Instantiate the class for extending click options
extend_cli = ExtendCLI(vars_input=yaml_vars, parameter_set=param_set, help_msg_map=option_help_messages)
# Detect command provider
global provider_cli
cli_provider = yamlr.deep_get(config, 'cli.providers.default', {})
cli_provider = yaml_vars.get('cli_provider', cli_provider)
if cli_provider == 'bash':
from libs.providers import bash as bash_cli
provider_cli = bash_cli.ProviderCLI()
elif cli_provider == 'vagrant':
from libs.providers import vagrant as vagrant_cli
provider_cli = vagrant_cli.ProviderCLI()
else:
from libs.providers import ansible as ansible_cli
provider_cli = ansible_cli.ProviderCLI()
# Activate any plugins if found
if os.path.isdir("plugins/providers"):
import plugins
global plugins
# Activate Plugins if any are found
plugin = plugins.Plugin(provider=cli_provider)
plugins = plugin.activatePlugins()
# CLI Provider Plugins
for provider in plugins.providers:
provider_cli = provider.ProviderCLI()
# Main CLI interface
click_help = """\b
Ansible Taskrunner - ansible-playbook wrapper
- YAML-abstracted python click cli options
- Utilizes a specially-formatted ansible-playbook (Taskfile.yaml)
to extend the ansible playbook command via
the python click module
"""
click_help_epilog = ""
@click.group(cls=ExtendedEpilog, help=click_help, epilog=click_help_epilog, context_settings=dict(max_content_width=help_max_content_width))
@click.version_option(version=__version__)
@click.option('--config', type=str, nargs=1,
help='Specify a config file (default is config.ini)')
@click.option('--debug', is_flag=True, help='Enable debug output')
@click.option('--silent', is_flag=True, help='Suppress all output')
@click.option('--verbose', count=True,
help='Increase verbosity of output')
@click.option('--log', is_flag=True, help='Enable output logging')
def cli(**kwargs):
global config, config_file, __debug, verbose, loglevel, logger, suppress_output
suppress_output = True if kwargs.get('silent') else False
# Are we specifying an alternate config file?
if kwargs['config']:
config = superconf.load_config(config_file)
if config is None:
logger.debug('No valid config file found %s' % config_file)
logger.debug('Using program defaults')
# Verbose mode enabled?
verbose = kwargs.get('verbose', None)
# Debug mode enabled?
__debug = kwargs.get('debug', None)
# Set up logging with our desired output level
if __debug:
loglevel = logging.DEBUG # 10
elif verbose:
loglevel = logging.INFO # 20
else:
loglevel = logging.INFO # 20
logger.setLevel(loglevel)
if suppress_output:
if sys.version_info[0] >= 3:
logging.disable(sys.maxsize) # Python 3
else:
logging.disable(sys.maxint) # Python 2
# Add the log file handler to the logger, if applicable
if kwargs.get('log') and not log_file:
logger.warning('Logging enabled, but no log_file specified in %s' % config_file)
if kwargs.get('log') and log_file:
filehandler = logging.handlers.RotatingFileHandler(
log_file, maxBytes=logging_maxBytes, backupCount=logging_backupCount)
formatter = logging.Formatter(logging_format)
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)
logger.debug('Debug Mode Enabled, keeping any generated temp files')
return
init_epilog = ''
if is_windows:
init_epilog = '''
Examples:
- Initialize an empty workspace
tasks init
- Initialize an empty workspace config with username and remote path
tasks init -h myhost.example.org -u {0} -r "/home/{0}/git/ansible"
'''.format(local_username)
# Init command
@cli.command(cls=ExtendedHelp, help='Initialize local directory with sample files',
epilog=init_epilog, context_settings=dict(max_content_width=180))
@click.version_option(version=__version__)
@click.option('---show-samples', is_flag=True,
help='Only show a sample task manifest, don\'t write it')
@extend_cli.bastion_mode
def init(**kwargs):
logger.info('Initializing ...')
if kwargs.get('_show_samples'):
logger.info('Displaying sample config')
print(SAMPLE_CONFIG)
logger.info('Displaying sample manifest')
print(SAMPLE_TASKS_MANIFEST)
if is_windows:
logger.info('Displaying sample sftp config')
print(SAMPLE_SFTP_CONFIG)
else:
if not os.path.exists(config_file):
logger.info(
'Existing config not found, writing %s' % config_file)
with open(config_file, 'w') as f:
f.write(SAMPLE_CONFIG)
else:
logger.info(
'File exists, not writing sample config %s' % config_file)
if not os.path.exists(tasks_file):
logger.info(
'Existing manifest not found, writing %s' % tasks_file)
with open(tasks_file, 'w') as f:
f.write(SAMPLE_TASKS_MANIFEST)
else:
logger.info(
'File exists, not writing manifest %s' % tasks_file)
if is_windows or kwargs.get('_bastion_mode'):
settings_vars = init_bastion_settings(kwargs)
if not os.path.exists(sftp_config_file):
logger.info(
'Existing sftp config not found, writing %s' % sftp_config_file)
with open(sftp_config_file, 'w') as f:
f.write(Template(SAMPLE_SFTP_CONFIG).safe_substitute(**settings_vars))
else:
logger.info(
'File exists, not writing sftp config %s' % sftp_config_file)
# Run command
# Parse help documentation
help_string = yamlr.deep_get(yaml_vars, 'help.message', 'Run the specified Taskfile')
help_string = Template(help_string).safe_substitute(**available_vars)
epilog_string = yamlr.deep_get(yaml_vars, 'help.epilog', '')
examples = yamlr.deep_get(yaml_vars, 'help.examples', '')
examples_string = ''
# Treat the make-mode internal bash functions
function_help_string = ''
# Bash functions
bash_functions = []
yaml_vars_functions = yaml_vars.get('functions', {})
internal_functions = {}
if yaml_vars_functions:
internal_functions = yaml_vars_functions
# Append the special make_mode_engage bash function
internal_functions['make_mode_engage'] = {
'help': 'Engage Make Mode',
'shell': 'bash',
'hidden': 'true',
'source': '''
echo Make Mode Engaged
echo Invoking ${1} function
${1}
'''
}
for f in internal_functions:
f_shell = yamlr.deep_get(yaml_vars, 'functions.%s.shell' % f, {})
source = yamlr.deep_get(yaml_vars, 'functions.%s.source' % f, {})
if f_shell and source:
function_source = shell_invocation_mappings[f_shell].format(src=source)
bash_functions.append(
'function {fn}(){{\n{fs}\n}}'.format(
fn=f, fs=function_source)
)
for f in internal_functions:
if yamlr.deep_get(internal_functions, '%s.hidden' % f, {}) or \
not yamlr.deep_get(internal_functions, '%s.help' % f, {}):
continue
f_help_string = internal_functions[f].get('help')
function_help_string += '{fn}: {hs}\n'.format(fn=f, hs=f_help_string)
if isinstance(examples, list):
for example in examples:
if isinstance(example, dict):
for key, value in example.items():
value = Template(value).safe_substitute(**available_vars)
examples_string += '- {k}:\n{v}'.format(k=key, v=value)
if isinstance(example, str):
example = Template(example).safe_substitute(**available_vars)
examples_string += '%s\n' % example
epilog = '''
{ep}
Examples:
{ex}
Available make-style functions:
{fh}
'''.format(ep=epilog_string,
ex=examples_string or 'None',
fh=function_help_string or 'None')
epilog = Template(epilog).safe_substitute(**available_vars)
@cli.command(cls=ExtendedHelp, help="{h}".format(h=help_string),
epilog=epilog)
@click.version_option(version=__version__)
@click.option('---make', 'make_mode_engage', is_flag=False,
help='Call make-style function',
required=False)
@click.option('---echo',
is_flag=True,
help='Don\'t run, simply echo underlying commands')
@extend_cli.options
@extend_cli.bastion_mode
@provider_cli.options
def run(args=None, **kwargs):
global param_set
# Process Raw Args
# Process run args, if any
args = ' '.join(args) if args else ''
# Silence Output if so required
# Initialize values for subshell
prefix = 'echo' if kwargs.get('_echo') else ''
# Are we executing commands via bastion host?
bastion_settings = {}
# Force bastion mode if running from a Windows host
bastion_mode_enabled = True if is_windows else kwargs.get('_bastion_mode', False)
if bastion_mode_enabled:
bastion_settings = {
'config_file': yamlr.deep_get(config, 'bastion_mode.config_file', 'sftp-config.json'),
# Turn bastion Mode off if we explicitly don't want it
'enabled': yamlr.deep_get(config, 'bastion_mode.enabled', True),
'keep_alive': yamlr.deep_get(config, 'bastion_mode.keep_alive', True),
'poll_wait_time': yamlr.deep_get(config, 'bastion_mode.poll_wait_time', 5),
'sftp_sync': yamlr.deep_get(config, 'bastion_mode.sync', True)
}
# Gather variables from commandline for interpolation
cli_vars = ''
# python 2.x
# Make sure kwargs adhere to the order in
# which they were called
if sys.version_info[0] < 3:
# First we build a mapping of cli variables to corresponding yaml variables
parameter_mapping = {}
req_parameters = yaml_vars.get('required_parameters', {}) or {}
opt_parameters = yaml_vars.get('optional_parameters', {}) or {}
# We need to 'inject' built-in cli options
# since we're artificially re-ordering things
ctx = click.get_current_context()
# Parse the help message to extract cli options
ctx_help = ctx.get_help()
existing_provider_options = re.findall('---.*?[\s]', ctx_help)
for opt in existing_provider_options:
opt = opt.strip()
opt_parameters[opt] = opt.replace('---', '_').replace('-', '_')
# We're working with the optional
# parameter set in either case
if req_parameters:
d_req = dict(req_parameters)
d_opt = dict(opt_parameters)
d_req.update(d_opt)
parameter_mapping = d_req
else:
parameter_mapping = dict(opt_parameters)
# Next, we create a dictionary that holds cli arguments
# in the order they were called, as per the parameter mapping
ordered_args = {}
for k, v in parameter_mapping.items():
for a in sys.argv:
try:
if re.match(k, a):
for o in k.split('|'):
if o in sys.argv:
i = sys.argv.index(o)
ordered_args[k] = i
except Exception as e:
logger.debug("Skipped {_k} due to error {_e}".format(_k=k, _e=e))
# Lastly, we convert our kwargs object to
# an ordered dictionary object as per the above
# making sure we include any existing kwargs items
ordered_args_tuples = []
for k, v in sorted(ordered_args.items(), key=lambda item: item[1]):
if isinstance(parameter_mapping[k], str):
o_tuple = (parameter_mapping[k], kwargs.get(parameter_mapping[k]))
kwargs.pop(parameter_mapping[k], None)
else:
logger.error('Unexpected parameter mapping "%s", check your cli invocation' % k)
sys.exit(1)
ordered_args_tuples.append(o_tuple)
new_kwargs = ordered_args_tuples + [(k,v) for k,v in kwargs.items()]
kwargs = OrderedDict(new_kwargs)
# cli-provided variables
# List-type variables
list_vars = []
for key, value in kwargs.items():
if key.startswith('_'):
cli_vars += '{k}="{v}"\n'.format(k=key, v=value)
elif value and key not in internal_functions.keys():
if isinstance(value, list) or isinstance(value, tuple):
list_vars.append('{k}=$(cat <<EOF\n{v}\nEOF\n)'.format(
k=key, v='\n'.join(value)))
else:
cli_vars += '{k}="{v}"\n'.format(k=key, v=value)
# Gather default variables
vars_list = []
kwargs_list = [(k,v) for k,v in kwargs.items() if v]
kwargs_dict_filtered = dict([(k,v) for k,v in kwargs.items() if v])
# Define the list of yaml variables, excluding the 'inventory' variable (if applicable)
yaml_variables = [(key,value) for key,value in yaml_vars.items() if not isinstance(value, dict) and not key == 'inventory']
# Define the list of default variables,
# ensuring we only keep those that were
# not overridden via cli option
for var in yaml_variables:
if var[0] not in [d[0] for d in kwargs_list]:
vars_list.append((var[0],var[1]))
else:
vars_list.append((var[0], kwargs_dict_filtered[var[0]]))
if sys.version_info[0] < 3:
default_vars = OrderedDict(vars_list)
else:
default_vars = dict(vars_list)
for var in default_vars:
if isinstance(default_vars[var], list):
_var = default_vars[var]
try:
list_vars.append('{k}=$(cat <<EOF\n{v}\nEOF\n)'.format(
k=var, v='\n'.join(_var)))
except TypeError as e:
logger.debug("Unsupported variable type, skipped variable '%s'" % var)
logger.debug("Skip Reason %s" % e)
# String-type variables
defaults_string_vars = []
for var in default_vars:
if isinstance(default_vars[var], str):
try:
_var = default_vars[var]
defaults_string_vars.append(
'{k}="""{v}"""'.format(k=var, v=_var))
except TypeError as e:
logger.debug("Unsupported variable type, skipped variable '%s'" % var)
logger.debug("Skip Reason %s" % e)
# Append the __tasks_file variable to the above list
defaults_string_vars.append(
'__tasks_file__=%s' % tf_path
)
inventory_variable = 'inventory="""{v}"""'.format(v=yamlr.deep_get(yaml_vars, 'inventory', ''))
defaults_string_vars.append(inventory_variable)
# Short-circuit the task runner
# if we're calling functions from the commandline
cli_functions = ['{k} {v}'.format(
k=key, v='' if value in [True, False] else value) for key, value in kwargs.items() if
value and key in internal_functions.keys()]
if cli_functions:
command = '''{clv}
{dsv}
{psv}
{dlv}
{bfn}
{clf} {arg} {raw}
'''.format(
dsv='\n'.join(defaults_string_vars),
psv=paramset_var,
dlv='\n'.join(list_vars),
clv=cli_vars,
bfn='\n'.join(bash_functions),
clf='\n'.join(cli_functions),
arg=args,
raw=raw_args
)
if prefix == 'echo':
print(command)
else:
sub_process.call(command, debug_enabled=__debug, suppress_output=suppress_output)
else:
# Invoke the cli provider
provider_cli.invocation(
args=args,
bash_functions=bash_functions,
bastion_settings=bastion_settings,
cli_vars=cli_vars,
debug=__debug,
default_vars=default_vars,
invocation=cli_invocation,
kwargs=kwargs,
paramset_var=paramset_var,
prefix=prefix,
raw_args=raw_args,
string_vars=defaults_string_vars,
suppress_output=suppress_output,
yaml_input_file=yaml_input_file,
yaml_vars=yaml_vars
)
if __name__ == '__main__':
sys.exit(cli())
|
{"/ansible_taskrunner/libs/cli/click_commands_init_sub.py": ["/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/options_advanced.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/sshutil/client.py": ["/ansible_taskrunner/libs/sshutil/sync.py", "/ansible_taskrunner/libs/sshutil/scp.py", "/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/config.py": ["/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/click_extras/help.py": ["/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/proc_mgmt/__init__.py": ["/ansible_taskrunner/libs/formatting/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_group.py": ["/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/language/__init__.py": ["/ansible_taskrunner/libs/superduperconfig/__init__.py"], "/ansible_taskrunner/libs/providers/vagrant.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/click_commands_create_sub.py": ["/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/defaults.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/cli/click_commands_create_init.py": ["/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py", "/ansible_taskrunner/logger.py"], "/ansible_taskrunner/libs/providers/bash.py": ["/ansible_taskrunner/libs/proc_mgmt/__init__.py"], "/ansible_taskrunner/libs/cli/invocation.py": ["/ansible_taskrunner/libs/errorhandler/__init__.py"], "/ansible_taskrunner/libs/click_extras/__init__.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/click_extras/options_advanced.py"], "/ansible_taskrunner/cli.py": ["/ansible_taskrunner/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/__init__.py"], "/ansible_taskrunner/libs/providers/ansible.py": ["/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/formatting/__init__.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/libs/sshutil/client.py", "/ansible_taskrunner/libs/bastion_mode/__init__.py", "/ansible_taskrunner/libs/help/__init__.py"], "/ansible_taskrunner/libs/sshutil/sync.py": ["/ansible_taskrunner/libs/sshutil/scp.py"], "/ansible_taskrunner/libs/cli/__init__.py": ["/ansible_taskrunner/config.py", "/ansible_taskrunner/libs/cli/invocation.py", "/ansible_taskrunner/libs/click_extras/__init__.py", "/ansible_taskrunner/libs/click_extras/help.py", "/ansible_taskrunner/libs/proc_mgmt/__init__.py", "/ansible_taskrunner/logger.py", "/ansible_taskrunner/libs/cli/click_commands_create_group.py", "/ansible_taskrunner/libs/cli/click_commands_create_init.py", "/ansible_taskrunner/libs/cli/click_commands_create_sub.py", "/ansible_taskrunner/libs/cli/click_commands_init_sub.py"]}
|
28,188,184
|
SanjaySajuJacob/Apollo-Hospital
|
refs/heads/master
|
/views.py
|
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from django.views import generic
from .models import Employee, Patients
# Create your views here.
def homepage(request):
return render(request, 'apollo/welcome.html')
def emploginpage(request):
if request.method == "POST":
if request.POST.get('EmpID'):
post = Employee(emp_id=request.POST.get('EmpID'))
post.save()
if request.POST.get('Full Name'):
post = Employee(emp_name=request.POST.get('Full Name'))
else:
return render(request, 'apollo/emploginpage.html')
def emploginpage(request):
if request.method == "POST":
if request.POST.get('EmpID'):
post = Employee(emp_id=request.POST.get('EmpID'))
post.save()
if request.POST.get('Full Name'):
post = Employee(emp_name=request.POST.get('Full Name'))
else:
return render(request, 'apollo/emploginpage.html')
|
{"/views.py": ["/models.py"]}
|
28,188,185
|
SanjaySajuJacob/Apollo-Hospital
|
refs/heads/master
|
/models.py
|
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Employee(models.Model):
emp_id = models.CharField(max_length = 100, primary_key = True)
emp_name = models.CharField(max_length = 100)
designation = models.CharField(max_length = 100)
department = models.CharField(max_length = 100)
class Accomodation(models.Model):
room_type = models.CharField(max_length = 100, primary_key = True)
no_of_beds_left = models.IntegerField(default = 100)
cost = models.IntegerField(default = 10000)
class Patients(models.Model):
patient_id = models.CharField(max_length = 100, primary_key = True)
patient_name = models.CharField(max_length = 100)
room_type = models.ForeignKey(Accomodation, on_delete = models.CASCADE)
age = models.IntegerField(default = 0)
phone_no = models.IntegerField(default = 9999999999)
profession = models.CharField(max_length = 100)
class EmpFinance(models.Model):
emp_id = models.ForeignKey(Employee, on_delete = models.CASCADE)
salary = models.IntegerField(default = 10000)
class PatFinance(models.Model):
patient_id = models.ForeignKey(Patients, on_delete = models.CASCADE)
payment_method = models.CharField(max_length = 100)
amount_paid = models.IntegerField(default = 0)
date = models.DateTimeField('payment_date')
class Vaccines(models.Model):
vaccine_name = models.CharField(max_length = 100, primary_key = True)
vaccine_stock = models.IntegerField(default = 100)
vaccine_cost = models.IntegerField(default = 1000)
class CovApply(models.Model):
patient_id = models.ForeignKey(Patients, on_delete = models.CASCADE)
vaccine_name = models.ForeignKey(Vaccines, on_delete = models.CASCADE)
covid_test_result = models.CharField(max_length = 10)
|
{"/views.py": ["/models.py"]}
|
28,188,186
|
SanjaySajuJacob/Apollo-Hospital
|
refs/heads/master
|
/urls.py
|
from django.urls import path
from . import views
app_name = 'apollo'
urlpatterns = [
path('', views.homepage, name = 'homepage'),
path('login', views.emploginpage, name = 'emploginpage'),
path('login', views.patloginpage, name = 'patloginpage'),
]
|
{"/views.py": ["/models.py"]}
|
28,189,864
|
matthewwithanm/django-imagekit
|
refs/heads/develop
|
/imagekit/processors/crop.py
|
import warnings
from pilkit.processors.crop import *
warnings.warn('imagekit.processors.crop is deprecated use imagekit.processors instead', DeprecationWarning)
__all__ = ['TrimBorderColor', 'Crop', 'SmartCrop']
|
{"/imagekit/models/fields/files.py": ["/imagekit/utils.py"], "/imagekit/utils.py": ["/imagekit/lib.py"], "/imagekit/__init__.py": ["/imagekit/specs/__init__.py", "/imagekit/pkgmeta.py", "/imagekit/registry.py"], "/tests/models.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/tests/test_optimistic_strategy.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/tests/utils.py"], "/tests/test_fields.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py", "/tests/models.py", "/tests/utils.py"], "/tests/test_serialization.py": ["/imagekit/cachefiles/__init__.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/tests/test_cachefiles.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/imagekit/templatetags/imagekit.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/registry.py"], "/tests/conftest.py": ["/tests/utils.py"], "/imagekit/cachefiles/namers.py": ["/imagekit/utils.py"], "/imagekit/forms/fields.py": ["/imagekit/specs/__init__.py", "/imagekit/utils.py"], "/imagekit/models/fields/__init__.py": ["/imagekit/registry.py", "/imagekit/specs/__init__.py", "/imagekit/specs/sourcegroups.py", "/imagekit/models/fields/files.py", "/imagekit/models/fields/utils.py"], "/imagekit/specs/sourcegroups.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_no_extra_queries.py": ["/tests/models.py"], "/imagekit/models/fields/utils.py": ["/imagekit/cachefiles/__init__.py"], "/imagekit/cachefiles/backends.py": ["/imagekit/utils.py"], "/tests/test_generateimage_tag.py": ["/tests/utils.py"], "/imagekit/cachefiles/__init__.py": ["/imagekit/files.py", "/imagekit/registry.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_thumbnail_tag.py": ["/tests/utils.py"], "/tests/test_settings.py": ["/imagekit/conf.py", "/imagekit/utils.py", "/tests/utils.py"], "/imagekit/files.py": ["/imagekit/utils.py"], "/tests/test_closing_fieldfiles.py": ["/tests/models.py", "/tests/utils.py"], "/imagekit/cachefiles/strategies.py": ["/imagekit/utils.py"], "/imagekit/registry.py": ["/imagekit/signals.py", "/imagekit/utils.py", "/imagekit/specs/sourcegroups.py", "/imagekit/cachefiles/__init__.py"], "/imagekit/generatorlibrary.py": ["/imagekit/processors/__init__.py", "/imagekit/registry.py", "/imagekit/specs/__init__.py"], "/tests/test_sourcegroups.py": ["/imagekit/signals.py", "/imagekit/specs/sourcegroups.py", "/tests/models.py", "/tests/utils.py"], "/tests/utils.py": ["/imagekit/cachefiles/backends.py", "/imagekit/conf.py", "/imagekit/utils.py", "/tests/models.py"], "/tests/test_abstract_models.py": ["/imagekit/utils.py", "/tests/models.py"], "/imagekit/management/commands/generateimages.py": ["/imagekit/registry.py"], "/tests/imagegenerators.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/imagekit/specs/__init__.py": ["/imagekit/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/imagekit/registry.py", "/imagekit/utils.py"]}
|
28,189,865
|
matthewwithanm/django-imagekit
|
refs/heads/develop
|
/imagekit/pkgmeta.py
|
__title__ = 'django-imagekit'
__author__ = 'Matthew Tretter, Venelin Stoykov, Eric Eldredge, Bryan Veloso, Greg Newman, Chris Drackett, Justin Driscoll'
__version__ = '4.1.0'
__license__ = 'BSD'
__all__ = ['__title__', '__author__', '__version__', '__license__']
|
{"/imagekit/models/fields/files.py": ["/imagekit/utils.py"], "/imagekit/utils.py": ["/imagekit/lib.py"], "/imagekit/__init__.py": ["/imagekit/specs/__init__.py", "/imagekit/pkgmeta.py", "/imagekit/registry.py"], "/tests/models.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/tests/test_optimistic_strategy.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/tests/utils.py"], "/tests/test_fields.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py", "/tests/models.py", "/tests/utils.py"], "/tests/test_serialization.py": ["/imagekit/cachefiles/__init__.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/tests/test_cachefiles.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/imagekit/templatetags/imagekit.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/registry.py"], "/tests/conftest.py": ["/tests/utils.py"], "/imagekit/cachefiles/namers.py": ["/imagekit/utils.py"], "/imagekit/forms/fields.py": ["/imagekit/specs/__init__.py", "/imagekit/utils.py"], "/imagekit/models/fields/__init__.py": ["/imagekit/registry.py", "/imagekit/specs/__init__.py", "/imagekit/specs/sourcegroups.py", "/imagekit/models/fields/files.py", "/imagekit/models/fields/utils.py"], "/imagekit/specs/sourcegroups.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_no_extra_queries.py": ["/tests/models.py"], "/imagekit/models/fields/utils.py": ["/imagekit/cachefiles/__init__.py"], "/imagekit/cachefiles/backends.py": ["/imagekit/utils.py"], "/tests/test_generateimage_tag.py": ["/tests/utils.py"], "/imagekit/cachefiles/__init__.py": ["/imagekit/files.py", "/imagekit/registry.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_thumbnail_tag.py": ["/tests/utils.py"], "/tests/test_settings.py": ["/imagekit/conf.py", "/imagekit/utils.py", "/tests/utils.py"], "/imagekit/files.py": ["/imagekit/utils.py"], "/tests/test_closing_fieldfiles.py": ["/tests/models.py", "/tests/utils.py"], "/imagekit/cachefiles/strategies.py": ["/imagekit/utils.py"], "/imagekit/registry.py": ["/imagekit/signals.py", "/imagekit/utils.py", "/imagekit/specs/sourcegroups.py", "/imagekit/cachefiles/__init__.py"], "/imagekit/generatorlibrary.py": ["/imagekit/processors/__init__.py", "/imagekit/registry.py", "/imagekit/specs/__init__.py"], "/tests/test_sourcegroups.py": ["/imagekit/signals.py", "/imagekit/specs/sourcegroups.py", "/tests/models.py", "/tests/utils.py"], "/tests/utils.py": ["/imagekit/cachefiles/backends.py", "/imagekit/conf.py", "/imagekit/utils.py", "/tests/models.py"], "/tests/test_abstract_models.py": ["/imagekit/utils.py", "/tests/models.py"], "/imagekit/management/commands/generateimages.py": ["/imagekit/registry.py"], "/tests/imagegenerators.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/imagekit/specs/__init__.py": ["/imagekit/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/imagekit/registry.py", "/imagekit/utils.py"]}
|
28,189,866
|
matthewwithanm/django-imagekit
|
refs/heads/develop
|
/imagekit/conf.py
|
from appconf import AppConf
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class ImageKitConf(AppConf):
CACHEFILE_NAMER = 'imagekit.cachefiles.namers.hash'
SPEC_CACHEFILE_NAMER = 'imagekit.cachefiles.namers.source_name_as_path'
CACHEFILE_DIR = 'CACHE/images'
DEFAULT_CACHEFILE_BACKEND = 'imagekit.cachefiles.backends.Simple'
DEFAULT_CACHEFILE_STRATEGY = 'imagekit.cachefiles.strategies.JustInTime'
DEFAULT_FILE_STORAGE = None
CACHE_BACKEND = None
CACHE_PREFIX = 'imagekit:'
CACHE_TIMEOUT = None
USE_MEMCACHED_SAFE_CACHE_KEY = True
def configure_cache_backend(self, value):
if value is None:
from django.core.cache import DEFAULT_CACHE_ALIAS
return DEFAULT_CACHE_ALIAS
if value not in settings.CACHES:
raise ImproperlyConfigured("{0} is not present in settings.CACHES".format(value))
return value
def configure_cache_timeout(self, value):
if value is None and settings.DEBUG:
# If value is not configured and is DEBUG set it to 5 minutes
return 300
# Otherwise leave it as is. If it is None then valies will never expire
return value
def configure_default_file_storage(self, value):
if value is None:
try:
from django.conf import DEFAULT_STORAGE_ALIAS
except ImportError: # Django < 4.2
return settings.DEFAULT_FILE_STORAGE
else:
return DEFAULT_STORAGE_ALIAS
return value
|
{"/imagekit/models/fields/files.py": ["/imagekit/utils.py"], "/imagekit/utils.py": ["/imagekit/lib.py"], "/imagekit/__init__.py": ["/imagekit/specs/__init__.py", "/imagekit/pkgmeta.py", "/imagekit/registry.py"], "/tests/models.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/tests/test_optimistic_strategy.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/tests/utils.py"], "/tests/test_fields.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py", "/tests/models.py", "/tests/utils.py"], "/tests/test_serialization.py": ["/imagekit/cachefiles/__init__.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/tests/test_cachefiles.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/imagekit/templatetags/imagekit.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/registry.py"], "/tests/conftest.py": ["/tests/utils.py"], "/imagekit/cachefiles/namers.py": ["/imagekit/utils.py"], "/imagekit/forms/fields.py": ["/imagekit/specs/__init__.py", "/imagekit/utils.py"], "/imagekit/models/fields/__init__.py": ["/imagekit/registry.py", "/imagekit/specs/__init__.py", "/imagekit/specs/sourcegroups.py", "/imagekit/models/fields/files.py", "/imagekit/models/fields/utils.py"], "/imagekit/specs/sourcegroups.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_no_extra_queries.py": ["/tests/models.py"], "/imagekit/models/fields/utils.py": ["/imagekit/cachefiles/__init__.py"], "/imagekit/cachefiles/backends.py": ["/imagekit/utils.py"], "/tests/test_generateimage_tag.py": ["/tests/utils.py"], "/imagekit/cachefiles/__init__.py": ["/imagekit/files.py", "/imagekit/registry.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_thumbnail_tag.py": ["/tests/utils.py"], "/tests/test_settings.py": ["/imagekit/conf.py", "/imagekit/utils.py", "/tests/utils.py"], "/imagekit/files.py": ["/imagekit/utils.py"], "/tests/test_closing_fieldfiles.py": ["/tests/models.py", "/tests/utils.py"], "/imagekit/cachefiles/strategies.py": ["/imagekit/utils.py"], "/imagekit/registry.py": ["/imagekit/signals.py", "/imagekit/utils.py", "/imagekit/specs/sourcegroups.py", "/imagekit/cachefiles/__init__.py"], "/imagekit/generatorlibrary.py": ["/imagekit/processors/__init__.py", "/imagekit/registry.py", "/imagekit/specs/__init__.py"], "/tests/test_sourcegroups.py": ["/imagekit/signals.py", "/imagekit/specs/sourcegroups.py", "/tests/models.py", "/tests/utils.py"], "/tests/utils.py": ["/imagekit/cachefiles/backends.py", "/imagekit/conf.py", "/imagekit/utils.py", "/tests/models.py"], "/tests/test_abstract_models.py": ["/imagekit/utils.py", "/tests/models.py"], "/imagekit/management/commands/generateimages.py": ["/imagekit/registry.py"], "/tests/imagegenerators.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/imagekit/specs/__init__.py": ["/imagekit/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/imagekit/registry.py", "/imagekit/utils.py"]}
|
28,189,867
|
matthewwithanm/django-imagekit
|
refs/heads/develop
|
/tests/models.py
|
from django.db import models
from imagekit import ImageSpec
from imagekit.models import ImageSpecField, ProcessedImageField
from imagekit.processors import Adjust, ResizeToFill, SmartCrop
class Thumbnail(ImageSpec):
processors = [ResizeToFill(100, 60)]
format = 'JPEG'
options = {'quality': 60}
class ImageModel(models.Model):
image = models.ImageField(upload_to='b')
class Photo(models.Model):
original_image = models.ImageField(upload_to='photos')
# Implicit source field
thumbnail = ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
ResizeToFill(50, 50)], format='JPEG',
options={'quality': 90})
smartcropped_thumbnail = ImageSpecField([Adjust(contrast=1.2,
sharpness=1.1), SmartCrop(50, 50)], source='original_image',
format='JPEG', options={'quality': 90})
class ProcessedImageFieldModel(models.Model):
processed = ProcessedImageField([SmartCrop(50, 50)], format='JPEG',
options={'quality': 90}, upload_to='p')
class ProcessedImageFieldWithSpecModel(models.Model):
processed = ProcessedImageField(spec=Thumbnail, upload_to='p')
class CountingCacheFileStrategy:
def __init__(self):
self.on_existence_required_count = 0
self.on_content_required_count = 0
self.on_source_saved_count = 0
def on_existence_required(self, file):
self.on_existence_required_count += 1
def on_content_required(self, file):
self.on_content_required_count += 1
def on_source_saved(self, file):
self.on_source_saved_count += 1
class AbstractImageModel(models.Model):
original_image = models.ImageField(upload_to='photos')
abstract_class_spec = ImageSpecField(source='original_image',
format='JPEG',
cachefile_strategy=CountingCacheFileStrategy())
class Meta:
abstract = True
class ConcreteImageModel(AbstractImageModel):
pass
class ConcreteImageModelSubclass(ConcreteImageModel):
pass
|
{"/imagekit/models/fields/files.py": ["/imagekit/utils.py"], "/imagekit/utils.py": ["/imagekit/lib.py"], "/imagekit/__init__.py": ["/imagekit/specs/__init__.py", "/imagekit/pkgmeta.py", "/imagekit/registry.py"], "/tests/models.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/tests/test_optimistic_strategy.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/tests/utils.py"], "/tests/test_fields.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py", "/tests/models.py", "/tests/utils.py"], "/tests/test_serialization.py": ["/imagekit/cachefiles/__init__.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/tests/test_cachefiles.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/cachefiles/backends.py", "/tests/imagegenerators.py", "/tests/utils.py"], "/imagekit/templatetags/imagekit.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/registry.py"], "/tests/conftest.py": ["/tests/utils.py"], "/imagekit/cachefiles/namers.py": ["/imagekit/utils.py"], "/imagekit/forms/fields.py": ["/imagekit/specs/__init__.py", "/imagekit/utils.py"], "/imagekit/models/fields/__init__.py": ["/imagekit/registry.py", "/imagekit/specs/__init__.py", "/imagekit/specs/sourcegroups.py", "/imagekit/models/fields/files.py", "/imagekit/models/fields/utils.py"], "/imagekit/specs/sourcegroups.py": ["/imagekit/cachefiles/__init__.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_no_extra_queries.py": ["/tests/models.py"], "/imagekit/models/fields/utils.py": ["/imagekit/cachefiles/__init__.py"], "/imagekit/cachefiles/backends.py": ["/imagekit/utils.py"], "/tests/test_generateimage_tag.py": ["/tests/utils.py"], "/imagekit/cachefiles/__init__.py": ["/imagekit/files.py", "/imagekit/registry.py", "/imagekit/signals.py", "/imagekit/utils.py"], "/tests/test_thumbnail_tag.py": ["/tests/utils.py"], "/tests/test_settings.py": ["/imagekit/conf.py", "/imagekit/utils.py", "/tests/utils.py"], "/imagekit/files.py": ["/imagekit/utils.py"], "/tests/test_closing_fieldfiles.py": ["/tests/models.py", "/tests/utils.py"], "/imagekit/cachefiles/strategies.py": ["/imagekit/utils.py"], "/imagekit/registry.py": ["/imagekit/signals.py", "/imagekit/utils.py", "/imagekit/specs/sourcegroups.py", "/imagekit/cachefiles/__init__.py"], "/imagekit/generatorlibrary.py": ["/imagekit/processors/__init__.py", "/imagekit/registry.py", "/imagekit/specs/__init__.py"], "/tests/test_sourcegroups.py": ["/imagekit/signals.py", "/imagekit/specs/sourcegroups.py", "/tests/models.py", "/tests/utils.py"], "/tests/utils.py": ["/imagekit/cachefiles/backends.py", "/imagekit/conf.py", "/imagekit/utils.py", "/tests/models.py"], "/tests/test_abstract_models.py": ["/imagekit/utils.py", "/tests/models.py"], "/imagekit/management/commands/generateimages.py": ["/imagekit/registry.py"], "/tests/imagegenerators.py": ["/imagekit/__init__.py", "/imagekit/processors/__init__.py"], "/imagekit/specs/__init__.py": ["/imagekit/__init__.py", "/imagekit/cachefiles/backends.py", "/imagekit/cachefiles/strategies.py", "/imagekit/registry.py", "/imagekit/utils.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.