byFormat returns a random example based on the format the user asks.
(a *AttributeExpr, r *ExampleGenerator)
| 194 | |
| 195 | // byFormat returns a random example based on the format the user asks. |
| 196 | func byFormat(a *AttributeExpr, r *ExampleGenerator) any { |
| 197 | if !hasFormatValidation(a) { |
| 198 | return nil |
| 199 | } |
| 200 | format := a.Validation.Format |
| 201 | if res, ok := map[ValidationFormat]any{ |
| 202 | FormatEmail: r.Email(), |
| 203 | FormatHostname: r.Hostname(), |
| 204 | FormatDate: time.Unix(int64(r.Int())%1454957045, 0).UTC().Format(time.DateOnly), // to obtain a "fixed" rand |
| 205 | FormatDateTime: time.Unix(int64(r.Int())%1454957045, 0).UTC().Format(time.RFC3339), // to obtain a "fixed" rand |
| 206 | FormatIPv4: r.IPv4Address().String(), |
| 207 | FormatIPv6: r.IPv6Address().String(), |
| 208 | FormatIP: r.IPv4Address().String(), |
| 209 | FormatURI: r.URL(), |
| 210 | FormatMAC: func() string { |
| 211 | res, err := syntax.Parse(`([0-9A-F]{2}-){5}[0-9A-F]{2}`, 0) |
| 212 | if err != nil { |
| 213 | return "12-34-56-78-9A-BC" |
| 214 | } |
| 215 | return patgen(res, r) |
| 216 | }(), |
| 217 | FormatCIDR: "192.168.100.14/24", |
| 218 | FormatRegexp: r.Characters(3) + ".*", |
| 219 | FormatRFC1123: time.Unix(int64(r.Int())%1454957045, 0).UTC().Format(time.RFC1123), // to obtain a "fixed" rand |
| 220 | FormatUUID: r.UUID(), |
| 221 | FormatJSON: `{"name":"example","email":"mail@example.com"}`, |
| 222 | }[format]; ok { |
| 223 | return res |
| 224 | } |
| 225 | panic("Validation: unknown format '" + format + "'") // bug |
| 226 | } |
| 227 | |
| 228 | // byPattern generates a random value that satisfies the pattern. |
| 229 | // |
no test coverage detected