MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / test_datetime_ms

Method test_datetime_ms

test/test_json_util.py:257–318  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

255 )
256
257 def test_datetime_ms(self):
258 # Test ISO8601 in-range
259 dat_min: dict[str, Any] = {"x": DatetimeMS(0)}
260 dat_max: dict[str, Any] = {"x": DatetimeMS(_MAX_UTC_MS)}
261 opts = JSONOptions(datetime_representation=DatetimeRepresentation.ISO8601)
262
263 self.assertEqual(
264 dat_min["x"].as_datetime(CodecOptions(tz_aware=False)),
265 json_util.loads(json_util.dumps(dat_min))["x"],
266 )
267 self.assertEqual(
268 dat_max["x"].as_datetime(CodecOptions(tz_aware=False)),
269 json_util.loads(json_util.dumps(dat_max))["x"],
270 )
271
272 # Test ISO8601 out-of-range
273 dat_min = {"x": DatetimeMS(-1)}
274 dat_max = {"x": DatetimeMS(_MAX_UTC_MS + 1)}
275
276 self.assertEqual('{"x": {"$date": {"$numberLong": "-1"}}}', json_util.dumps(dat_min))
277 self.assertEqual(
278 '{"x": {"$date": {"$numberLong": "' + str(int(dat_max["x"])) + '"}}}',
279 json_util.dumps(dat_max),
280 )
281 # Test legacy.
282 opts = JSONOptions(
283 datetime_representation=DatetimeRepresentation.LEGACY, json_mode=JSONMode.LEGACY
284 )
285 self.assertEqual('{"x": {"$date": -1}}', json_util.dumps(dat_min, json_options=opts))
286 self.assertEqual(
287 '{"x": {"$date": ' + str(int(dat_max["x"])) + "}}",
288 json_util.dumps(dat_max, json_options=opts),
289 )
290
291 # Test regular.
292 opts = JSONOptions(
293 datetime_representation=DatetimeRepresentation.NUMBERLONG, json_mode=JSONMode.LEGACY
294 )
295 self.assertEqual(
296 '{"x": {"$date": {"$numberLong": "-1"}}}', json_util.dumps(dat_min, json_options=opts)
297 )
298 self.assertEqual(
299 '{"x": {"$date": {"$numberLong": "' + str(int(dat_max["x"])) + '"}}}',
300 json_util.dumps(dat_max, json_options=opts),
301 )
302
303 # Test decode from datetime.datetime to DatetimeMS
304 dat_min = {"x": datetime.datetime.min}
305 dat_max = {"x": DatetimeMS(_MAX_UTC_MS).as_datetime(CodecOptions(tz_aware=False))}
306 opts = JSONOptions(
307 datetime_representation=DatetimeRepresentation.ISO8601,
308 datetime_conversion=DatetimeConversion.DATETIME_MS,
309 )
310
311 self.assertEqual(
312 DatetimeMS(dat_min["x"]),
313 json_util.loads(json_util.dumps(dat_min), json_options=opts)["x"],
314 )

Callers

nothing calls this directly

Calls 4

DatetimeMSClass · 0.90
JSONOptionsClass · 0.90
CodecOptionsClass · 0.90
as_datetimeMethod · 0.45

Tested by

no test coverage detected