我使用 Django Rest Framework APIClient 对 Django API 进行了一些单元测试。API 的不同端点返回自定义错误消息,其中一些带有格式化字符串,例如:'Geometry type "{}" is not supported'。
我断言来自客户端响应和错误消息键的状态代码,但在某些情况下,我想弄清楚返回了什么错误消息,以确保没有其他原因导致该错误。
所以我也想根据原始的未格式化字符串验证返回的错误消息。例如,如果我收到类似 的错误消息'Geometry type "Point" is not supported',我想检查它是否与原始未格式化的消息匹配,即'Geometry type "{}" is not supported'。
目前我想到的解决方案:
首先:用正则表达式模式替换原始字符串中的括号,然后查看它是否与响应匹配。
第二:(很酷的想法,但在某些情况下可能会失败)使用difflib.SequenceMatcher并测试相似度是否大于例如 90%。
这是一个例子:
有许多dict错误消息,每个错误都会从中选择相关消息,根据需要添加格式参数,然后引发错误:
ERROR_MESSAGES = {
'ERROR_1': 'Error message 1: {}. Do something about it',
'ERROR_2': 'Something went wrong',
'ERROR_3': 'Check you args: {}. Here is an example: {}'
}
Run Code Online (Sandbox Code Playgroud)
现在,我的 DRF 序列化器在处理请求期间发生错误,并引发错误:
try:
some_validation()
except SomeError as …Run Code Online (Sandbox Code Playgroud) 这是我的models.py:
def set_image(instance):
return Image.objects.filter(user=instance.user)[0]
class User(models.Model):
user = models.CharField(max_length=50)
class Image(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to='media')
class Item(models.Model):
user = models.ForeignKey(User)
image = models.ForeignKey(
Image,
blank=True,
null=True,
on_delete=models.SET(set_image)
)
Run Code Online (Sandbox Code Playgroud)
当我删除一个'Image'时,它的相关'Item'调用set_image,它返回一个错误,因为models.SET没有将实例传递给callable.我该如何改变这种行为?我应该覆盖models.SET还是有其他方法吗?
假设我有一些重叠的图层,每个图层都有一个点击事件.当我点击地图时,我想知道点击了哪些图层,尽管点击事件在第一层之后停止并且不会传播到其底层.我怎样才能做到这一点?
这是一个示例小提琴及其代码:https://jsfiddle.net/r0r0xLoc/
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(mymap).on('click', function() {
console.log('clicked on 1st polygon')
});
L.polygon([
[51.609, -0.1],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(mymap).on('click', function() {
console.log('clicked on 2nd polygon')
});
</script>
Run Code Online (Sandbox Code Playgroud)
如果单击每个多边形,则会看到其相关消息.如果单击重叠部分,则只能看到第二个多边形的消息.
django ×2
assertions ×1
foreign-keys ×1
javascript ×1
leaflet ×1
python ×1
string ×1
unit-testing ×1