How to use from_json method in pandera

Best Python code snippet using pandera_python

web_audio.py

Source:web_audio.py Github

copy

Full Screen

...15 '''16 def to_json(self) -> str:17 return self18 @classmethod19 def from_json(cls, json: str) -> GraphObjectId:20 return cls(json)21 def __repr__(self):22 return 'GraphObjectId({})'.format(super().__repr__())23class ContextType(enum.Enum):24 '''25 Enum of BaseAudioContext types26 '''27 REALTIME = "realtime"28 OFFLINE = "offline"29 def to_json(self):30 return self.value31 @classmethod32 def from_json(cls, json):33 return cls(json)34class ContextState(enum.Enum):35 '''36 Enum of AudioContextState from the spec37 '''38 SUSPENDED = "suspended"39 RUNNING = "running"40 CLOSED = "closed"41 def to_json(self):42 return self.value43 @classmethod44 def from_json(cls, json):45 return cls(json)46class NodeType(str):47 '''48 Enum of AudioNode types49 '''50 def to_json(self) -> str:51 return self52 @classmethod53 def from_json(cls, json: str) -> NodeType:54 return cls(json)55 def __repr__(self):56 return 'NodeType({})'.format(super().__repr__())57class ChannelCountMode(enum.Enum):58 '''59 Enum of AudioNode::ChannelCountMode from the spec60 '''61 CLAMPED_MAX = "clamped-max"62 EXPLICIT = "explicit"63 MAX_ = "max"64 def to_json(self):65 return self.value66 @classmethod67 def from_json(cls, json):68 return cls(json)69class ChannelInterpretation(enum.Enum):70 '''71 Enum of AudioNode::ChannelInterpretation from the spec72 '''73 DISCRETE = "discrete"74 SPEAKERS = "speakers"75 def to_json(self):76 return self.value77 @classmethod78 def from_json(cls, json):79 return cls(json)80class ParamType(str):81 '''82 Enum of AudioParam types83 '''84 def to_json(self) -> str:85 return self86 @classmethod87 def from_json(cls, json: str) -> ParamType:88 return cls(json)89 def __repr__(self):90 return 'ParamType({})'.format(super().__repr__())91class AutomationRate(enum.Enum):92 '''93 Enum of AudioParam::AutomationRate from the spec94 '''95 A_RATE = "a-rate"96 K_RATE = "k-rate"97 def to_json(self):98 return self.value99 @classmethod100 def from_json(cls, json):101 return cls(json)102@dataclass103class ContextRealtimeData:104 '''105 Fields in AudioContext that change in real-time.106 '''107 #: The current context time in second in BaseAudioContext.108 current_time: float109 #: The time spent on rendering graph divided by render qunatum duration,110 #: and multiplied by 100. 100 means the audio renderer reached the full111 #: capacity and glitch may occur.112 render_capacity: float113 #: A running mean of callback interval.114 callback_interval_mean: float115 #: A running variance of callback interval.116 callback_interval_variance: float117 def to_json(self):118 json = dict()119 json['currentTime'] = self.current_time120 json['renderCapacity'] = self.render_capacity121 json['callbackIntervalMean'] = self.callback_interval_mean122 json['callbackIntervalVariance'] = self.callback_interval_variance123 return json124 @classmethod125 def from_json(cls, json):126 return cls(127 current_time=float(json['currentTime']),128 render_capacity=float(json['renderCapacity']),129 callback_interval_mean=float(json['callbackIntervalMean']),130 callback_interval_variance=float(json['callbackIntervalVariance']),131 )132@dataclass133class BaseAudioContext:134 '''135 Protocol object for BaseAudioContext136 '''137 context_id: GraphObjectId138 context_type: ContextType139 context_state: ContextState140 #: Platform-dependent callback buffer size.141 callback_buffer_size: float142 #: Number of output channels supported by audio hardware in use.143 max_output_channel_count: float144 #: Context sample rate.145 sample_rate: float146 realtime_data: typing.Optional[ContextRealtimeData] = None147 def to_json(self):148 json = dict()149 json['contextId'] = self.context_id.to_json()150 json['contextType'] = self.context_type.to_json()151 json['contextState'] = self.context_state.to_json()152 json['callbackBufferSize'] = self.callback_buffer_size153 json['maxOutputChannelCount'] = self.max_output_channel_count154 json['sampleRate'] = self.sample_rate155 if self.realtime_data is not None:156 json['realtimeData'] = self.realtime_data.to_json()157 return json158 @classmethod159 def from_json(cls, json):160 return cls(161 context_id=GraphObjectId.from_json(json['contextId']),162 context_type=ContextType.from_json(json['contextType']),163 context_state=ContextState.from_json(json['contextState']),164 callback_buffer_size=float(json['callbackBufferSize']),165 max_output_channel_count=float(json['maxOutputChannelCount']),166 sample_rate=float(json['sampleRate']),167 realtime_data=ContextRealtimeData.from_json(json['realtimeData']) if 'realtimeData' in json else None,168 )169@dataclass170class AudioListener:171 '''172 Protocol object for AudioListner173 '''174 listener_id: GraphObjectId175 context_id: GraphObjectId176 def to_json(self):177 json = dict()178 json['listenerId'] = self.listener_id.to_json()179 json['contextId'] = self.context_id.to_json()180 return json181 @classmethod182 def from_json(cls, json):183 return cls(184 listener_id=GraphObjectId.from_json(json['listenerId']),185 context_id=GraphObjectId.from_json(json['contextId']),186 )187@dataclass188class AudioNode:189 '''190 Protocol object for AudioNode191 '''192 node_id: GraphObjectId193 context_id: GraphObjectId194 node_type: NodeType195 number_of_inputs: float196 number_of_outputs: float197 channel_count: float198 channel_count_mode: ChannelCountMode199 channel_interpretation: ChannelInterpretation200 def to_json(self):201 json = dict()202 json['nodeId'] = self.node_id.to_json()203 json['contextId'] = self.context_id.to_json()204 json['nodeType'] = self.node_type.to_json()205 json['numberOfInputs'] = self.number_of_inputs206 json['numberOfOutputs'] = self.number_of_outputs207 json['channelCount'] = self.channel_count208 json['channelCountMode'] = self.channel_count_mode.to_json()209 json['channelInterpretation'] = self.channel_interpretation.to_json()210 return json211 @classmethod212 def from_json(cls, json):213 return cls(214 node_id=GraphObjectId.from_json(json['nodeId']),215 context_id=GraphObjectId.from_json(json['contextId']),216 node_type=NodeType.from_json(json['nodeType']),217 number_of_inputs=float(json['numberOfInputs']),218 number_of_outputs=float(json['numberOfOutputs']),219 channel_count=float(json['channelCount']),220 channel_count_mode=ChannelCountMode.from_json(json['channelCountMode']),221 channel_interpretation=ChannelInterpretation.from_json(json['channelInterpretation']),222 )223@dataclass224class AudioParam:225 '''226 Protocol object for AudioParam227 '''228 param_id: GraphObjectId229 node_id: GraphObjectId230 context_id: GraphObjectId231 param_type: ParamType232 rate: AutomationRate233 default_value: float234 min_value: float235 max_value: float236 def to_json(self):237 json = dict()238 json['paramId'] = self.param_id.to_json()239 json['nodeId'] = self.node_id.to_json()240 json['contextId'] = self.context_id.to_json()241 json['paramType'] = self.param_type.to_json()242 json['rate'] = self.rate.to_json()243 json['defaultValue'] = self.default_value244 json['minValue'] = self.min_value245 json['maxValue'] = self.max_value246 return json247 @classmethod248 def from_json(cls, json):249 return cls(250 param_id=GraphObjectId.from_json(json['paramId']),251 node_id=GraphObjectId.from_json(json['nodeId']),252 context_id=GraphObjectId.from_json(json['contextId']),253 param_type=ParamType.from_json(json['paramType']),254 rate=AutomationRate.from_json(json['rate']),255 default_value=float(json['defaultValue']),256 min_value=float(json['minValue']),257 max_value=float(json['maxValue']),258 )259def enable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]:260 '''261 Enables the WebAudio domain and starts sending context lifetime events.262 '''263 cmd_dict: T_JSON_DICT = {264 'method': 'WebAudio.enable',265 }266 json = yield cmd_dict267def disable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]:268 '''269 Disables the WebAudio domain.270 '''271 cmd_dict: T_JSON_DICT = {272 'method': 'WebAudio.disable',273 }274 json = yield cmd_dict275def get_realtime_data(276 context_id: GraphObjectId277 ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,ContextRealtimeData]:278 '''279 Fetch the realtime data from the registered contexts.280 :param context_id:281 :returns: 282 '''283 params: T_JSON_DICT = dict()284 params['contextId'] = context_id.to_json()285 cmd_dict: T_JSON_DICT = {286 'method': 'WebAudio.getRealtimeData',287 'params': params,288 }289 json = yield cmd_dict290 return ContextRealtimeData.from_json(json['realtimeData'])291@event_class('WebAudio.contextCreated')292@dataclass293class ContextCreated:294 '''295 Notifies that a new BaseAudioContext has been created.296 '''297 context: BaseAudioContext298 @classmethod299 def from_json(cls, json: T_JSON_DICT) -> ContextCreated:300 return cls(301 context=BaseAudioContext.from_json(json['context'])302 )303@event_class('WebAudio.contextWillBeDestroyed')304@dataclass305class ContextWillBeDestroyed:306 '''307 Notifies that an existing BaseAudioContext will be destroyed.308 '''309 context_id: GraphObjectId310 @classmethod311 def from_json(cls, json: T_JSON_DICT) -> ContextWillBeDestroyed:312 return cls(313 context_id=GraphObjectId.from_json(json['contextId'])314 )315@event_class('WebAudio.contextChanged')316@dataclass317class ContextChanged:318 '''319 Notifies that existing BaseAudioContext has changed some properties (id stays the same)..320 '''321 context: BaseAudioContext322 @classmethod323 def from_json(cls, json: T_JSON_DICT) -> ContextChanged:324 return cls(325 context=BaseAudioContext.from_json(json['context'])326 )327@event_class('WebAudio.audioListenerCreated')328@dataclass329class AudioListenerCreated:330 '''331 Notifies that the construction of an AudioListener has finished.332 '''333 listener: AudioListener334 @classmethod335 def from_json(cls, json: T_JSON_DICT) -> AudioListenerCreated:336 return cls(337 listener=AudioListener.from_json(json['listener'])338 )339@event_class('WebAudio.audioListenerWillBeDestroyed')340@dataclass341class AudioListenerWillBeDestroyed:342 '''343 Notifies that a new AudioListener has been created.344 '''345 context_id: GraphObjectId346 listener_id: GraphObjectId347 @classmethod348 def from_json(cls, json: T_JSON_DICT) -> AudioListenerWillBeDestroyed:349 return cls(350 context_id=GraphObjectId.from_json(json['contextId']),351 listener_id=GraphObjectId.from_json(json['listenerId'])352 )353@event_class('WebAudio.audioNodeCreated')354@dataclass355class AudioNodeCreated:356 '''357 Notifies that a new AudioNode has been created.358 '''359 node: AudioNode360 @classmethod361 def from_json(cls, json: T_JSON_DICT) -> AudioNodeCreated:362 return cls(363 node=AudioNode.from_json(json['node'])364 )365@event_class('WebAudio.audioNodeWillBeDestroyed')366@dataclass367class AudioNodeWillBeDestroyed:368 '''369 Notifies that an existing AudioNode has been destroyed.370 '''371 context_id: GraphObjectId372 node_id: GraphObjectId373 @classmethod374 def from_json(cls, json: T_JSON_DICT) -> AudioNodeWillBeDestroyed:375 return cls(376 context_id=GraphObjectId.from_json(json['contextId']),377 node_id=GraphObjectId.from_json(json['nodeId'])378 )379@event_class('WebAudio.audioParamCreated')380@dataclass381class AudioParamCreated:382 '''383 Notifies that a new AudioParam has been created.384 '''385 param: AudioParam386 @classmethod387 def from_json(cls, json: T_JSON_DICT) -> AudioParamCreated:388 return cls(389 param=AudioParam.from_json(json['param'])390 )391@event_class('WebAudio.audioParamWillBeDestroyed')392@dataclass393class AudioParamWillBeDestroyed:394 '''395 Notifies that an existing AudioParam has been destroyed.396 '''397 context_id: GraphObjectId398 node_id: GraphObjectId399 param_id: GraphObjectId400 @classmethod401 def from_json(cls, json: T_JSON_DICT) -> AudioParamWillBeDestroyed:402 return cls(403 context_id=GraphObjectId.from_json(json['contextId']),404 node_id=GraphObjectId.from_json(json['nodeId']),405 param_id=GraphObjectId.from_json(json['paramId'])406 )407@event_class('WebAudio.nodesConnected')408@dataclass409class NodesConnected:410 '''411 Notifies that two AudioNodes are connected.412 '''413 context_id: GraphObjectId414 source_id: GraphObjectId415 destination_id: GraphObjectId416 source_output_index: typing.Optional[float]417 destination_input_index: typing.Optional[float]418 @classmethod419 def from_json(cls, json: T_JSON_DICT) -> NodesConnected:420 return cls(421 context_id=GraphObjectId.from_json(json['contextId']),422 source_id=GraphObjectId.from_json(json['sourceId']),423 destination_id=GraphObjectId.from_json(json['destinationId']),424 source_output_index=float(json['sourceOutputIndex']) if 'sourceOutputIndex' in json else None,425 destination_input_index=float(json['destinationInputIndex']) if 'destinationInputIndex' in json else None426 )427@event_class('WebAudio.nodesDisconnected')428@dataclass429class NodesDisconnected:430 '''431 Notifies that AudioNodes are disconnected. The destination can be null, and it means all the outgoing connections from the source are disconnected.432 '''433 context_id: GraphObjectId434 source_id: GraphObjectId435 destination_id: GraphObjectId436 source_output_index: typing.Optional[float]437 destination_input_index: typing.Optional[float]438 @classmethod439 def from_json(cls, json: T_JSON_DICT) -> NodesDisconnected:440 return cls(441 context_id=GraphObjectId.from_json(json['contextId']),442 source_id=GraphObjectId.from_json(json['sourceId']),443 destination_id=GraphObjectId.from_json(json['destinationId']),444 source_output_index=float(json['sourceOutputIndex']) if 'sourceOutputIndex' in json else None,445 destination_input_index=float(json['destinationInputIndex']) if 'destinationInputIndex' in json else None446 )447@event_class('WebAudio.nodeParamConnected')448@dataclass449class NodeParamConnected:450 '''451 Notifies that an AudioNode is connected to an AudioParam.452 '''453 context_id: GraphObjectId454 source_id: GraphObjectId455 destination_id: GraphObjectId456 source_output_index: typing.Optional[float]457 @classmethod458 def from_json(cls, json: T_JSON_DICT) -> NodeParamConnected:459 return cls(460 context_id=GraphObjectId.from_json(json['contextId']),461 source_id=GraphObjectId.from_json(json['sourceId']),462 destination_id=GraphObjectId.from_json(json['destinationId']),463 source_output_index=float(json['sourceOutputIndex']) if 'sourceOutputIndex' in json else None464 )465@event_class('WebAudio.nodeParamDisconnected')466@dataclass467class NodeParamDisconnected:468 '''469 Notifies that an AudioNode is disconnected to an AudioParam.470 '''471 context_id: GraphObjectId472 source_id: GraphObjectId473 destination_id: GraphObjectId474 source_output_index: typing.Optional[float]475 @classmethod476 def from_json(cls, json: T_JSON_DICT) -> NodeParamDisconnected:477 return cls(478 context_id=GraphObjectId.from_json(json['contextId']),479 source_id=GraphObjectId.from_json(json['sourceId']),480 destination_id=GraphObjectId.from_json(json['destinationId']),481 source_output_index=float(json['sourceOutputIndex']) if 'sourceOutputIndex' in json else None...

Full Screen

Full Screen

test_fields.py

Source:test_fields.py Github

copy

Full Screen

...8class DateTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring9 date = Date()10 def compare_dates(self, dt1, dt2, expected_delta):11 assert (dt1 - dt2) == expected_delta, ((((str(dt1) + '-') + str(dt2)) + '!=') + str(expected_delta))12 def test_from_json(self):13 """Test conversion from iso compatible date strings to struct_time"""14 self.compare_dates(15 DateTest.date.from_json("2013-01-01"),16 DateTest.date.from_json("2012-12-31"),17 datetime.timedelta(days=1)18 )19 self.compare_dates(20 DateTest.date.from_json("2013-01-01T00"),21 DateTest.date.from_json("2012-12-31T23"),22 datetime.timedelta(hours=1)23 )24 self.compare_dates(25 DateTest.date.from_json("2013-01-01T00:00"),26 DateTest.date.from_json("2012-12-31T23:59"),27 datetime.timedelta(minutes=1)28 )29 self.compare_dates(30 DateTest.date.from_json("2013-01-01T00:00:00"),31 DateTest.date.from_json("2012-12-31T23:59:59"),32 datetime.timedelta(seconds=1)33 )34 self.compare_dates(35 DateTest.date.from_json("2013-01-01T00:00:00Z"),36 DateTest.date.from_json("2012-12-31T23:59:59Z"),37 datetime.timedelta(seconds=1)38 )39 self.compare_dates(40 DateTest.date.from_json("2012-12-31T23:00:01-01:00"),41 DateTest.date.from_json("2013-01-01T00:00:00+01:00"),42 datetime.timedelta(hours=1, seconds=1)43 )44 def test_enforce_type(self):45 assert DateTest.date.enforce_type(None) is None46 assert DateTest.date.enforce_type('') is None47 assert DateTest.date.enforce_type('2012-12-31T23:00:01') ==\48 datetime.datetime(2012, 12, 31, 23, 0, 1, tzinfo=UTC)49 assert DateTest.date.enforce_type(1234567890000) == datetime.datetime(2009, 2, 13, 23, 31, 30, tzinfo=UTC)50 assert DateTest.date.enforce_type(datetime.datetime(2014, 5, 9, 21, 1, 27, tzinfo=UTC)) ==\51 datetime.datetime(2014, 5, 9, 21, 1, 27, tzinfo=UTC)52 with pytest.raises(TypeError):53 DateTest.date.enforce_type([1])54 def test_return_None(self):55 assert DateTest.date.from_json('') is None56 assert DateTest.date.from_json(None) is None57 with pytest.raises(TypeError):58 DateTest.date.from_json(['unknown value'])59 def test_old_due_date_format(self):60 current = datetime.datetime.today()61 assert datetime.datetime(current.year, 3, 12, 12, tzinfo=UTC) == DateTest.date.from_json('March 12 12:00')62 assert datetime.datetime(current.year, 12, 4, 16, 30, tzinfo=UTC) == DateTest.date.from_json('December 4 16:30')63 assert DateTest.date.from_json('12 12:00') is None64 def test_non_std_from_json(self):65 """66 Test the non-standard args being passed to from_json67 """68 now = datetime.datetime.now(UTC)69 delta = now - datetime.datetime.fromtimestamp(0, UTC)70 assert DateTest.date.from_json(delta.total_seconds() * 1000) == now71 yesterday = datetime.datetime.now(UTC) - datetime.timedelta(days=-1)72 assert DateTest.date.from_json(yesterday) == yesterday73 def test_to_json(self):74 """75 Test converting time reprs to iso dates76 """77 assert DateTest.date.to_json(datetime.datetime.strptime('2012-12-31T23:59:59Z', '%Y-%m-%dT%H:%M:%SZ')) ==\78 '2012-12-31T23:59:59Z'79 assert DateTest.date.to_json(DateTest.date.from_json('2012-12-31T23:59:59Z')) == '2012-12-31T23:59:59Z'80 assert DateTest.date.to_json(DateTest.date.from_json('2012-12-31T23:00:01-01:00')) ==\81 '2012-12-31T23:00:01-01:00'82 with pytest.raises(TypeError):83 DateTest.date.to_json('2012-12-31T23:00:01-01:00')84class TimedeltaTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring85 delta = Timedelta()86 def test_from_json(self):87 assert TimedeltaTest.delta.from_json('1 day 12 hours 59 minutes 59 seconds') ==\88 datetime.timedelta(days=1, hours=12, minutes=59, seconds=59)89 assert TimedeltaTest.delta.from_json('1 day 46799 seconds') == datetime.timedelta(days=1, seconds=46799)90 def test_enforce_type(self):91 assert TimedeltaTest.delta.enforce_type(None) is None92 assert TimedeltaTest.delta.enforce_type(datetime.timedelta(days=1, seconds=46799)) ==\93 datetime.timedelta(days=1, seconds=46799)94 assert TimedeltaTest.delta.enforce_type('1 day 46799 seconds') == datetime.timedelta(days=1, seconds=46799)95 with pytest.raises(TypeError):96 TimedeltaTest.delta.enforce_type([1])97 def test_to_json(self):98 assert '1 days 46799 seconds' ==\99 TimedeltaTest.delta.to_json(datetime.timedelta(days=1, hours=12, minutes=59, seconds=59))100class TimeInfoTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring101 def test_time_info(self):102 due_date = datetime.datetime(2000, 4, 14, 10, tzinfo=UTC)103 grace_pd_string = '1 day 12 hours 59 minutes 59 seconds'104 timeinfo = TimeInfo(due_date, grace_pd_string)105 assert timeinfo.close_date == (due_date + Timedelta().from_json(grace_pd_string))106class RelativeTimeTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring107 delta = RelativeTime()108 def test_from_json(self):109 assert RelativeTimeTest.delta.from_json('0:05:07') == datetime.timedelta(seconds=307)110 assert RelativeTimeTest.delta.from_json(100.0) == datetime.timedelta(seconds=100)111 assert RelativeTimeTest.delta.from_json(None) == datetime.timedelta(seconds=0)112 with pytest.raises(TypeError):113 RelativeTimeTest.delta.from_json(1234) # int114 with pytest.raises(ValueError):115 RelativeTimeTest.delta.from_json("77:77:77")116 def test_enforce_type(self):117 assert RelativeTimeTest.delta.enforce_type(None) is None118 assert RelativeTimeTest.delta.enforce_type(datetime.timedelta(days=1, seconds=46799)) ==\119 datetime.timedelta(days=1, seconds=46799)120 assert RelativeTimeTest.delta.enforce_type('0:05:07') == datetime.timedelta(seconds=307)121 with pytest.raises(TypeError):122 RelativeTimeTest.delta.enforce_type([1])123 def test_to_json(self):124 assert '01:02:03' == RelativeTimeTest.delta.to_json(datetime.timedelta(seconds=3723))125 assert '00:00:00' == RelativeTimeTest.delta.to_json(None)126 assert '00:01:40' == RelativeTimeTest.delta.to_json(100.0)127 error_msg = "RelativeTime max value is 23:59:59=86400.0 seconds, but 90000.0 seconds is passed"128 with self.assertRaisesRegex(ValueError, error_msg):129 RelativeTimeTest.delta.to_json(datetime.timedelta(seconds=90000))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pandera automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful