mirror of
				https://github.com/fjosw/pyerrors.git
				synced 2025-10-31 07:45:45 +01:00 
			
		
		
		
	[Feat] Prevent objects with uuid names to be serialized to json.
This commit is contained in:
		
					parent
					
						
							
								779dedf5b3
							
						
					
				
			
			
				commit
				
					
						5c4f44fa01
					
				
			
		
					 2 changed files with 18 additions and 0 deletions
				
			
		|  | @ -59,6 +59,8 @@ def create_json_string(ol, description='', indent=1): | |||
|     def _gen_cdata_d_from_list(ol): | ||||
|         dl = [] | ||||
|         for name in ol[0].cov_names: | ||||
|             if _is_uuid4_hex(name): | ||||
|                 raise ValueError("Cannot safely serialize an Obs derived from a Meas object with a uuid as name. Consider recreating the Meas with an explict name.") | ||||
|             ed = {} | ||||
|             ed['id'] = name | ||||
|             ed['layout'] = str(ol[0].covobs[name].cov.shape).lstrip('(').rstrip(')').rstrip(',') | ||||
|  | @ -216,6 +218,11 @@ def create_json_string(ol, description='', indent=1): | |||
|         return json.dumps(d, indent=indent, ensure_ascii=False, default=_jsonifier, write_mode=json.WM_COMPACT) | ||||
| 
 | ||||
| 
 | ||||
| def _is_uuid4_hex(s): | ||||
|     uuid4_hex_pattern = re.compile(r'^[0-9a-f]{32}$') | ||||
|     return bool(uuid4_hex_pattern.match(s)) | ||||
| 
 | ||||
| 
 | ||||
| def dump_to_json(ol, fname, description='', indent=1, gz=True): | ||||
|     """Export a list of Obs or structures containing Obs to a .json(.gz) file. | ||||
|     Dict keys that are not JSON-serializable such as floats are converted to strings. | ||||
|  |  | |||
|  | @ -409,3 +409,14 @@ def assert_equal_Obs(to, ro): | |||
|                 print(kw, "does not match.") | ||||
|                 return False | ||||
|     return True | ||||
| 
 | ||||
| 
 | ||||
| def test_meas_uuid(tmp_path): | ||||
|     meas = pe.Meas(0.3, 0.2) | ||||
| 
 | ||||
|     for obs in [meas, meas + 1, meas * pe.pseudo_Obs(0.1, 0.001, "obs|r1")]: | ||||
|         with pytest.raises(ValueError): | ||||
|             jsonio.dump_to_json([obs], "test_file", indent=1, description='[This file should not be writable]') | ||||
| 
 | ||||
|     name_meas = pe.Meas(0.3, 0.2, name="my name") | ||||
|     jsonio.dump_to_json([name_meas], "test_file", indent=1, description='[This file should be writable]') | ||||
|  |  | |||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue