from typing import Optional
@dataclass
class Event:
id: str
created_at: datetime
updated_at: Optional[datetime]
#updated_at: datetime = field(default_factory=datetime.now) CASE 1
#updated_at: Optional[datetime] = None CASE 2
@dataclass
class NamedEvent(Event):
name: str
Run Code Online (Sandbox Code Playgroud)
创建事件实例时,我通常不会有updated_at字段。current time在数据库中进行插入时,我可以传递作为默认值或添加一个值,并在对象的后续使用中获取它。哪种方法更好?根据我的理解,我无法在不通过case1 和 case2 中的 updated_at字段的NamedEvent情况下创建实例,因为我在 name 字段中没有默认值。
我创建了一个发出 HTTParty get 请求的函数。它会引发我需要测试的自定义错误消息。我尝试在测试中使用 Webmock 来存根请求,但它引发了<Net::OpenTimeout>. 如果 url 是动态构造的,我如何存根 get 请求?
def function(a , b)
# some logic , dynamic url constructed
response = HTTParty.get(url, headers: {"Content-Type" =>
"application/json"})
if response.code != 200
raise CustomError.new <<~EOF
Error while fetching job details.
Response code: #{response.code}
Response body: #{response.body}
EOF
end
JSON.parse(response.body)
Run Code Online (Sandbox Code Playgroud)
为了测试
def test_function
WebMock.stub_request(:get, url).with(:headers => {'Content-
Type'=>'application/json'}).to_return(:status => 500)
# HTTParty.stub(get: fake_response)
err = assert_raises CustumError do
c.function(a , b)
end
Run Code Online (Sandbox Code Playgroud)