Skip to content

Commit

Permalink
chore: Update python codegen
Browse files Browse the repository at this point in the history
  • Loading branch information
kulikthebird committed Dec 10, 2024
1 parent f3f338c commit d2b5896
Show file tree
Hide file tree
Showing 9 changed files with 240 additions and 69 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/cw-schema-codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,6 @@ rand = { version = "0.8.5", features = ["min_const_gen"] }
serde = { workspace = true, features = ["derive"] }
serde_json = "1.0.128"
tempfile = "3.14.0"
cosmwasm-std = { version = "2.2.0-rc.1", path = "../std", default-features = false, features = [
"std",
] }
9 changes: 4 additions & 5 deletions packages/cw-schema-codegen/src/python/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn expand_node_name<'a>(
match node.value {
cw_schema::NodeType::Array { items } => {
let items = &schema.definitions[items];
format!("{}[]", expand_node_name(schema, items)).into()
format!("typing.List[{}]", expand_node_name(schema, items)).into()
}
cw_schema::NodeType::Float => "float".into(),
cw_schema::NodeType::Double => "float".into(),
Expand All @@ -35,12 +35,11 @@ fn expand_node_name<'a>(
format!("[{}]", items).into()
}
cw_schema::NodeType::Enum { .. } => node.name.as_ref().into(),

cw_schema::NodeType::Decimal { .. } => "decimal.Decimal".into(),
cw_schema::NodeType::Address => "str".into(),
cw_schema::NodeType::Checksum => todo!(),
cw_schema::NodeType::HexBinary => todo!(),
cw_schema::NodeType::Timestamp => todo!(),
cw_schema::NodeType::Checksum => "str".into(),
cw_schema::NodeType::HexBinary => "str".into(),
cw_schema::NodeType::Timestamp => "str".into(),
cw_schema::NodeType::Unit => "None".into(),
}
}
Expand Down
16 changes: 8 additions & 8 deletions packages/cw-schema-codegen/templates/python/struct.tpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@
{% match ty %}
{% when TypeTemplate::Unit %}
class {{ name }}(RootModel):
'''{% for doc in docs %}
"""{% for doc in docs %}
{{ doc }}
{% endfor %}'''
{% endfor %}"""
root: None
{% when TypeTemplate::Tuple with (types) %}
class {{ name }}(RootModel):
'''{% for doc in docs %}
"""{% for doc in docs %}
{{ doc }}
{% endfor %}'''
{% endfor %}"""
root: typing.Tuple[{{ types|join(", ") }}]
{% when TypeTemplate::Named with { fields } %}
class {{ name }}(BaseModel):
'''{% for doc in docs %}
"""{% for doc in docs %}
{{ doc }}
{% endfor %}'''
{% endfor %}"""
{% for field in fields %}
{{ field.name }}: {{ field.ty }}
'''{% for doc in field.docs %}
"""{% for doc in field.docs %}
# {{ doc }}
{% endfor %}'''
{% endfor %}"""
{% endfor %}
{% endmatch %}
139 changes: 89 additions & 50 deletions packages/cw-schema-codegen/tests/python_tpl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,65 @@ use cw_schema::Schemaifier;
use serde::{Deserialize, Serialize};
use std::io::Write;

#[derive(Schemaifier, Serialize, Deserialize)]
/// This is a struct level documentation for enum type
#[derive(Schemaifier, Serialize, Deserialize, PartialEq, Debug)]
pub enum SomeEnum {
/// Field1 docs
Field1,

/// Field2 docs
Field2(u32, u32),
Field3 { a: String, b: u32 },
// Field4(Box<SomeEnum>), // TODO tkulik: Do we want to support Box<T> ?
// Field5 { a: Box<SomeEnum> },

/// Field3 docs
Field3 {
/// `a` field docs
a: String,

/// `b` field docs
b: u32,
},
}

#[derive(Schemaifier, Serialize, Deserialize)]
/// This is a struct level documentation for unit struct
#[derive(Schemaifier, Serialize, Deserialize, PartialEq, Debug)]
pub struct UnitStructure;

#[derive(Schemaifier, Serialize, Deserialize)]
/// This is a struct level documentation for tuple
#[derive(Schemaifier, Serialize, Deserialize, PartialEq, Debug)]
pub struct TupleStructure(u32, String, u128);

#[derive(Schemaifier, Serialize, Deserialize)]
/// This is a struct level documentation for named structure
#[derive(Schemaifier, Serialize, Deserialize, PartialEq, Debug)]
pub struct NamedStructure {
/// `a` field docs
a: String,

/// `b` field docs
b: u8,

/// `c` field docs
c: SomeEnum,
}

#[derive(Schemaifier, Serialize, Deserialize, PartialEq, Debug)]
pub struct AllSimpleTypesAndDocs {
array_field: Vec<String>,
float_field: f32,
double_field: f64,
bool_field: bool,
string_field: String,
int_field: i64,
bytes_field: cosmwasm_std::Binary,
opt_field: Option<String>,
byte_field: u8,
decimal_field: cosmwasm_std::Decimal,
address_field: cosmwasm_std::Addr,
checksum_field: cosmwasm_std::Checksum,
hexbinary_field: cosmwasm_std::HexBinary,
timestamp_field: cosmwasm_std::Timestamp,
unit_field: (),
}

#[test]
fn simple_enum() {
// generate the schemas for each of the above types
Expand Down Expand Up @@ -55,61 +92,63 @@ fn simple_enum() {
}

macro_rules! validator {
($typ:ty) => {{
let a: Box<dyn FnOnce(&str)> = Box::new(|output| {
serde_json::from_str::<$typ>(output).unwrap();
});
a
($typ:ty, $example:expr) => {{
(
stringify!($typ),
cw_schema::schema_of::<$typ>(),
serde_json::to_string(&$example).unwrap(),
{
let a: Box<dyn FnOnce(&str)> = Box::new(|output| {
let result = serde_json::from_str::<$typ>(output).unwrap();
assert_eq!(result, $example);
});
a
},
)
}};
}

#[test]
fn assert_validity() {
let schemas = [
(
"SomeEnum",
cw_schema::schema_of::<SomeEnum>(),
serde_json::to_string(&SomeEnum::Field1).unwrap(),
validator!(SomeEnum),
),
(
"SomeEnum",
cw_schema::schema_of::<SomeEnum>(),
serde_json::to_string(&SomeEnum::Field2(10, 23)).unwrap(),
validator!(SomeEnum),
),
(
"SomeEnum",
cw_schema::schema_of::<SomeEnum>(),
serde_json::to_string(&SomeEnum::Field3 {
validator!(SomeEnum, SomeEnum::Field1),
validator!(SomeEnum, SomeEnum::Field2(10, 23)),
validator!(
SomeEnum,
SomeEnum::Field3 {
a: "sdf".to_string(),
b: 12,
})
.unwrap(),
validator!(SomeEnum),
),
(
"UnitStructure",
cw_schema::schema_of::<UnitStructure>(),
serde_json::to_string(&UnitStructure {}).unwrap(),
validator!(UnitStructure),
}
),
(
"TupleStructure",
cw_schema::schema_of::<TupleStructure>(),
serde_json::to_string(&TupleStructure(10, "aasdf".to_string(), 2)).unwrap(),
validator!(TupleStructure),
),
(
"NamedStructure",
cw_schema::schema_of::<NamedStructure>(),
serde_json::to_string(&NamedStructure {
validator!(UnitStructure, UnitStructure {}),
validator!(TupleStructure, TupleStructure(10, "aasdf".to_string(), 2)),
validator!(
NamedStructure,
NamedStructure {
a: "awer".to_string(),
b: 4,
c: SomeEnum::Field1,
})
.unwrap(),
validator!(NamedStructure),
}
),
validator!(
AllSimpleTypesAndDocs,
AllSimpleTypesAndDocs {
array_field: vec!["abc".to_string(), "def".to_string()],
float_field: 10.2,
double_field: 10.232323,
bool_field: true,
string_field: "sdfsdf".to_string(),
int_field: -10,
bytes_field: cosmwasm_std::Binary::new(vec![0x1, 0x2, 0x3]),
opt_field: Some("sdfsdfwer".to_string()),
byte_field: 9,
decimal_field: cosmwasm_std::Decimal::one(),
address_field: cosmwasm_std::Addr::unchecked("some_address"),
checksum_field: cosmwasm_std::Checksum::generate(&[0x10]),
hexbinary_field: cosmwasm_std::HexBinary::from_hex("FAFAFA").unwrap(),
timestamp_field: cosmwasm_std::Timestamp::from_seconds(100),
unit_field: (),
}
),
];

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
source: packages/cw-schema-codegen/tests/python_tpl.rs
expression: output
snapshot_kind: text
---
# This code is @generated by cw-schema-codegen. Do not modify this manually.

import typing
import decimal
from pydantic import BaseModel, RootModel



class UnitStructure(RootModel):
"""
This is a struct level documentation for unit struct
"""
root: None
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
source: packages/cw-schema-codegen/tests/python_tpl.rs
expression: output
snapshot_kind: text
---
# This code is @generated by cw-schema-codegen. Do not modify this manually.

import typing
import decimal
from pydantic import BaseModel, RootModel



class TupleStructure(RootModel):
"""
This is a struct level documentation for tuple
"""
root: typing.Tuple[int, str, int]
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
source: packages/cw-schema-codegen/tests/python_tpl.rs
expression: output
snapshot_kind: text
---
# This code is @generated by cw-schema-codegen. Do not modify this manually.

import typing
import decimal
from pydantic import BaseModel, RootModel

class SomeEnum(RootModel):
"""
This is a struct level documentation for enum type
"""



class Field1(RootModel):
"""
Field1 docs
"""
root: typing.Literal['Field1']



class Field2(BaseModel):
"""
Field2 docs
"""
Field2: typing.Tuple[int, int]



class Field3(BaseModel):
class __Inner(BaseModel):
"""
Field3 docs
"""

a: str
"""
`a` field docs
"""

b: int
"""
`b` field docs
"""

Field3: __Inner


root: typing.Union[ Field1, Field2, Field3, ]
# This code is @generated by cw-schema-codegen. Do not modify this manually.

import typing
import decimal
from pydantic import BaseModel, RootModel



class NamedStructure(BaseModel):
"""
This is a struct level documentation for named structure
"""

a: str
"""
# `a` field docs
"""

b: int
"""
# `b` field docs
"""

c: SomeEnum
"""
# `c` field docs
"""
Loading

0 comments on commit d2b5896

Please sign in to comment.