我正在尝试使用Pythons mock包来模拟Pythons requests模块.让我在以下场景中工作的基本要求是什么?
在我的views.py中,我有一个函数可以使每次request.get()调用具有不同的响应
def myview(request):
res1 = requests.get('aurl')
res2 = request.get('burl')
res3 = request.get('curl')
Run Code Online (Sandbox Code Playgroud)
在我的测试类中,我想做类似的事情,但无法弄清楚确切的方法调用
步骤1:
# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'
Run Code Online (Sandbox Code Playgroud)
第2步:
打电话给我
第3步:
验证响应包含'响应','b响应','c响应'
如何完成步骤1(模拟请求模块)?
我的桌子看起来像
create table try ( name varchar(8), CREATED_BY varchar(40) not null);
Run Code Online (Sandbox Code Playgroud)
然后我有一个触发器来自动填充CREATED_BY字段
create trigger autoPopulateAtInsert BEFORE INSERT on try for each row set new.CREATED_BY=user();
Run Code Online (Sandbox Code Playgroud)
当我使用插入时
insert into try (name) values ('abc');
Run Code Online (Sandbox Code Playgroud)
该条目在表中进行,但我仍然收到错误消息
Field 'CREATED_BY' doesn't have a default value Error no 1364
Run Code Online (Sandbox Code Playgroud)
有没有办法抑制这个错误而不使字段可以为空并且不删除触发器?否则我的hibernate将看到这些异常(即使已经进行了插入),然后应用程序将崩溃.
我有字符串
'星期四2011年10月20日00:00:00 GMT-0400(东部夏令时)'
并希望以dd/mm/yyyy格式获取日期.如何使用jquery日期选择器库执行此操作?
我有以下简单的类:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties({ "thirdField" })
public class Message {
private TypeA type;
private String producer;
//Getters and Setters
}
Run Code Online (Sandbox Code Playgroud)
在我的测试课上
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public void testMethd() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.USE_ANNOTATIONS, true);
Class<T> instanceType = Message.class;
String msgBody = "{\"producer\": \"clientApp\", \"type\": \"aType\", \"thirdField\": []}";
objectMapper.readValue(msgBody, instanceType);
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的就是将上面的json字符串转换为Message类并忽略'thirdField'.但我一直在努力
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "thirdField" (class Message), not marked as ignorable (2 known properties: , "type", "producer"])
Run Code Online (Sandbox Code Playgroud) 我有一个用例,我使用多部分uplaod上传数百个文件到我的S3桶.每次上传后,我需要确保上传的文件没有损坏(基本上检查数据完整性).目前,在上传文件后,我重新下载并计算内容字符串上的md5,并将其与本地文件的md5进行比较.所以像
conn = S3Connection('access key', 'secretkey')
bucket = conn.get_bucket('bucket_name')
source_path = 'file_to_upload'
source_size = os.stat(source_path).st_size
mp = bucket.initiate_multipart_upload(os.path.basename(source_path))
chunk_size = 52428800
chunk_count = int(math.ceil(source_size / chunk_size))
for i in range(chunk_count + 1):
offset = chunk_size * i
bytes = min(chunk_size, source_size - offset)
with FileChunkIO(source_path, 'r', offset=offset,
bytes=bytes) as fp:
mp.upload_part_from_file(fp, part_num=i + 1, md5=k.compute_md5(fp, bytes))
mp.complete_upload()
obj_key = bucket.get_key('file_name')
print(obj_key.md5) #prints None
print(obj_key.base64md5) #prints None
content = bucket.get_key('file_name').get_contents_as_string()
# compute the md5 on content
Run Code Online (Sandbox Code Playgroud)
这种方法浪费,因为它使带宽使用量增加了一倍.我试过了
bucket.get_key('file_name').md5
bucket.get_key('file_name').base64md5
Run Code Online (Sandbox Code Playgroud)
但都返回无.
有没有其他方法来实现md5而不下载整个东西?
我在我的spring应用程序中有一个classX,我希望能够找出所有spring bean是否已经初始化.为此,我正在尝试监听ContextRefreshedEvent.
到目前为止,我有以下代码,但我不确定这是否足够.
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public classX implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个方法如下
public class ClientClass {
public void clientMethod() {
while(true){
doSomethings.....
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用mockito进行测试。我能够调用 clientMethod,但由于 clientMethod 内部有 while(true),因此该调用永远不会返回,并且我永远不会到达我的断言语句,这些语句(当然)是在 clientMethod() 调用之后发生的。有没有办法在我的测试用例的一次循环迭代后停止循环?
我有一个
LoadingCache<Long, String> idNameMap
Run Code Online (Sandbox Code Playgroud)
需要填充。这些 id 在我的应用程序上下文中是唯一的。但是,由于数据存储在表中的方式,我需要将额外的参数传递给数据库查询以完成快速的数据库查找。这意味着我应该能够将这些参数传递给我的 loadAll 方法,它目前看起来像:
@Override
public Map<Long, String> loadAll(Iterable idsIterable) throws Exception {
//pass in ids and extra parameters to improve database query speed
}
Run Code Online (Sandbox Code Playgroud)
这些额外的参数不需要成为我的缓存的一部分。我的问题是我应该使用什么模式来解决这个问题?
在我的settings.py中,我将缓存指定为:
CACHES = {
'default': {
......
}
}
Run Code Online (Sandbox Code Playgroud)
在我的views.py中,我有
import requests
from django.core.cache import cache, get_cache
def aview():
#check cache
if not get_cache('default').get('key'):
#make request and save in cache
result = request.get('some_url')
get_cache('default').set('key', result)
return result
else:
return get_cache('default').get('key')
Run Code Online (Sandbox Code Playgroud)
现在在我的tests.py中,我已经能够模拟requests.get('aurl'),这样就可以确保没有外部请求.
但是测试代码仍然会访问缓存并从中获取/设置.因此,如果我的prod已经设置了缓存,则测试失败,因为它从相同的缓存中获取数据.或者,如果我首先运行我的测试,那么测试用例是使用测试数据设置缓存,并且当我运行prod网站时,我看到相同的情况.
我该如何模拟调用
get_cache('default').set('key', result)
Run Code Online (Sandbox Code Playgroud)
和
get_cache('default').get('key')
Run Code Online (Sandbox Code Playgroud)
这样set set不会设置真正的缓存(返回None?)并且get不会返回实际缓存中的任何内容.
请向我提供如何完成此操作的代码示例.
这是我如何模仿我的请求
def test_get_aview(self):
with mock.patch('requests.get') as mymock:
mymock.side_effect = (lambda url: MOCKED_DATA[url])
Run Code Online (Sandbox Code Playgroud)
我可以在此之后添加什么代码才能使其正常工作?我试过类似的东西
class MockCacheValue(mock.MagicMock):
def get(self, key):
print 'here'
return None
def set(self, key, value):
print 'here 2'
pass …Run Code Online (Sandbox Code Playgroud) 我在git中有以下结构
scripts/
scripts/folder1/
scripts/folder1/module
scripts/folder1/module/setup.py
scripts/folder1/module/src/module
scripts/folder1/module/src/module/__init__.py
scripts/folder1/module/src/module/source.py
Run Code Online (Sandbox Code Playgroud)
我想安装模块,所以我在requirements.txt中尝试了以下内容
git+https://user@bitbucket.org/repo-name/scripts.git#egg=module&subdirectory=module
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用,我得到以下错误:
IOError: [Errno 2] No such file or directory: '/private/var/folders/p_/gz96g4610fn94hz6w_l2gjyw0000gn/T/pip-build-MLhekq/module/module/setup.py
Run Code Online (Sandbox Code Playgroud)
我知道这个问题可能已经解答了如何从一个带有pip的git子目录安装?但我正在寻找我的确切语法.
在我的 Django 应用程序中的某个位置,我对我的视图进行了 Ajax 调用
$.post("/metrics", {
'program': 'AWebsite',
'marketplace': 'Japan',
'metrics': {'pageLoadTime': '1024'}
});
Run Code Online (Sandbox Code Playgroud)
在我的Python代码中,我有
@require_POST
def metrics(request):
program = request.POST.get('program', '')
marketplace = request.POST.get('marketplace', '')
metrics = request.POST.get('metrics', '')
reportMetrics(metrics, program, marketplace)
Run Code Online (Sandbox Code Playgroud)
python 中的函数metrics()应该reportMetrics()使用这些参数进行调用,然后这些参数应该进入日志文件。但在我的日志文件中,我没有看到“pageLoadTime”值 - 可能是因为它是作为字典传入的。将来我需要向其中添加更多项目,因此它需要保留为字典(而不是像前两个那样的字符串)。
将传入的 javascript 字典转换为 python 字典的最简单方法是什么?