在以下bash 语句中,-a
和-n
选项执行了哪些功能if
?
if [ -n "$1" -a -n "$2" -a -n "$3" ]; then
REFNAME=$(basename $3)
else
Run Code Online (Sandbox Code Playgroud)
是-a
和-n
所谓的初选?
是否-a file
意味着"如果文件存在则为真."?
我试图模拟我班级方法中使用的open函数.我找到了这个线程如何模拟with语句中使用的open(在Python中使用Mock框架)?但无法解决我的问题.单元测试文档也显示了一个解决方案,它也没有模拟我的开放式https://docs.python.org/3/library/unittest.mock-examples.html#patch-decorators
这是我的类使用open函数的方法:
#__init.py__
import json
class MyClass:
def save_data_to_file(self, data):
with open('/tmp/data.json', 'w') as file:
json.dump(data, file)
...
mc = MyClass()
Run Code Online (Sandbox Code Playgroud)
现在我找到了一个不同的解决方案.这是我的测试:
#save_to_file_test.py
from mymodule import MyClass
from mock import mock_open, patch
import ast
class SaveToFileTest(unittest.TestCase):
def setUp(self):
self.mc = MyClass()
self.data = [
{'id': 5414470, 'name': 'peter'},
{'id': 5414472, 'name': 'tom'},
{'id': 5414232, 'name': 'pit'},
]
def test_save_data_to_file(self):
m = mock_open()
with patch('mymodule.open', m, create=True):
self.mc.save_data_to_file(self.data)
string = ''
for call in m.return_value.write.mock_calls:
string += (call[1][0]) …
Run Code Online (Sandbox Code Playgroud) 我正在尝试覆盖名为Invoice的模型的delete方法.Model Invoice在模型Action中由ForeignKey引用.我想在删除Invoice时更新名为模型Admin的BillingField
这篇文章描述的解决方案:
如何覆盖模型上的delete()并使其仍然可以使用相关的删除
答案:https: //stackoverflow.com/a/1539182
在models.py中这样对我不起作用:
def delete(self):
Action.objects.filter(invoice=self).update(billed=False) # and tried 0 instead of False
super(Invoice,self).delete()
Run Code Online (Sandbox Code Playgroud)
还尝试过:
def delete(self):
actions = Action.objects.filter(invoice=self)
for action in actions:
action.billed=False # and tried 0 instead of False
action.save()
super(Invoice,self).delete()
Run Code Online (Sandbox Code Playgroud)
模型操作中的ForeignKey字段具有on_delete = models.SET_NULL,以避免在删除发票时删除操作.但是我还需要将结账设置为False.
invoice = models.ForeignKey( Invoice, verbose_name = 'Rechnung', null=True, blank=True,on_delete=models.SET_NULL)
Run Code Online (Sandbox Code Playgroud)
我刚刚在这里阅读https://code.djangoproject.com/ticket/10751,在管理员中,所选的动作删除无法用delete()覆盖
我必须使用delete_view()
所以我试过了
def delete_selected(self, request, obj, extra_context=None):
Action.objects.filter(invoice=self).update(billed=False)
super(InvoiceAdmin, self).delete_view(request, obj, extra_context)
Run Code Online (Sandbox Code Playgroud)
也尝试使用obj而不是self,但不是解决方案