Best K6 code snippet using json.getValidator
validator_test.go
Source:validator_test.go
...9 "os"10 "strings"11 "testing"12)13func getValidator(t *testing.T, bagName, profileName string) *bagit.Validator {14 profilePath, err := testutil.GetPathToTestProfile(profileName)15 require.Nil(t, err)16 profile, err := bagit.LoadBagItProfile(profilePath)17 require.Nil(t, err)18 bagPath, err := testutil.GetPathToTestBag(bagName)19 require.Nil(t, err)20 bag := bagit.NewBag(bagPath)21 return bagit.NewValidator(bag, profile)22}23func TestNewValidator(t *testing.T) {24 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")25 assert.NotNil(t, validator)26}27func TestReadBag(t *testing.T) {28 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")29 require.NotNil(t, validator)30 validator.ReadBag()31 assert.Empty(t, validator.Errors())32 // Make sure files were added as the right types, in the right places.33 assert.Equal(t, 4, len(validator.Bag.Payload))34 assert.Equal(t, 2, len(validator.Bag.Manifests))35 assert.Equal(t, 2, len(validator.Bag.TagManifests))36 assert.Equal(t, 8, len(validator.Bag.TagFiles))37 assert.NotEmpty(t, validator.Bag.Payload["data/datastream-DC"])38 assert.NotEmpty(t, validator.Bag.Payload["data/datastream-descMetadata"])39 assert.NotEmpty(t, validator.Bag.Payload["data/datastream-MARC"])40 assert.NotEmpty(t, validator.Bag.Payload["data/datastream-RELS-EXT"])41 assert.NotEmpty(t, validator.Bag.Manifests["manifest-md5.txt"])42 assert.NotEmpty(t, validator.Bag.Manifests["manifest-sha256.txt"])43 assert.NotEmpty(t, validator.Bag.TagManifests["tagmanifest-md5.txt"])44 assert.NotEmpty(t, validator.Bag.TagManifests["tagmanifest-sha256.txt"])45 assert.NotEmpty(t, validator.Bag.TagFiles["aptrust-info.txt"])46 assert.NotEmpty(t, validator.Bag.TagFiles["bag-info.txt"])47 assert.NotEmpty(t, validator.Bag.TagFiles["bagit.txt"])48 assert.NotEmpty(t, validator.Bag.TagFiles["custom_tag_file.txt"])49 assert.NotEmpty(t, validator.Bag.TagFiles["junk_file.txt"])50 assert.NotEmpty(t, validator.Bag.TagFiles["custom_tags/tracked_file_custom.xml"])51 assert.NotEmpty(t, validator.Bag.TagFiles["custom_tags/tracked_tag_file.txt"])52 assert.NotEmpty(t, validator.Bag.TagFiles["custom_tags/untracked_tag_file.txt"])53 // Manifests should have been parsed.54 for _, m := range validator.Bag.Manifests {55 assert.Equal(t, 4, m.ParsedData.Count())56 }57 md5, err := validator.Bag.GetChecksumFromManifest(constants.MD5, "data/datastream-DC")58 require.Nil(t, err)59 sha256, err := validator.Bag.GetChecksumFromManifest(constants.SHA256, "data/datastream-DC")60 require.Nil(t, err)61 assert.Equal(t, "44d85cf4810d6c6fe87750117633e461", md5)62 assert.Equal(t, "248fac506a5c46b3c760312b99827b6fb5df4698d6cf9a9cdc4c54746728ab99", sha256)63 // TagManifests should have been parsed.64 for _, m := range validator.Bag.TagManifests {65 assert.Equal(t, 8, m.ParsedData.Count())66 }67 md5, err = validator.Bag.GetChecksumFromTagManifest(constants.MD5, "aptrust-info.txt")68 require.Nil(t, err)69 sha256, err = validator.Bag.GetChecksumFromTagManifest(constants.SHA256, "aptrust-info.txt")70 require.Nil(t, err)71 assert.Equal(t, "300e936e622605f9f7a846d261d53093", md5)72 assert.Equal(t, "a2b6c5a713af771c5e4edde8d5be25fbcad86e45ea338f43a5bb769347e7c8bb", sha256)73 // Files in BagItProfile.TagFilesRequired should be parsed,74 // while others should not.75 unparsedTagFile := validator.Bag.TagFiles["custom_tags/tracked_tag_file.txt"]76 assert.Equal(t, 0, unparsedTagFile.ParsedData.Count())77 parsedTagFile := validator.Bag.TagFiles["aptrust-info.txt"]78 require.NotEqual(t, 0, parsedTagFile.ParsedData.Count())79 require.Equal(t, 1, len(parsedTagFile.ParsedData.FindByKey("Title")))80 require.Equal(t, 1, len(parsedTagFile.ParsedData.FindByKey("Access")))81 assert.Equal(t, "Thirteen Ways of Looking at a Blackbird", parsedTagFile.ParsedData.FindByKey("Title")[0].Value)82 assert.Equal(t, "Institution", parsedTagFile.ParsedData.FindByKey("Access")[0].Value)83}84func TestValidateTopLevelFiles(t *testing.T) {85 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")86 require.NotNil(t, validator)87 validator.Profile.AllowMiscTopLevelFiles = true88 validator.ReadBag()89 assert.True(t, validator.ValidateTopLevelFiles())90 assert.Empty(t, validator.Errors())91 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")92 require.NotNil(t, validator)93 // Items in the top-level dir that are not manifests or required94 // tag files are considered misc. The APTrust BagIt profile95 // defines 3 of the 5 non-manifest items in the top-level dir96 // as required (bagit, bag-info, aptrust-info), so the other two97 // are misc.98 validator.Profile.AllowMiscTopLevelFiles = false99 validator.ReadBag()100 assert.False(t, validator.ValidateTopLevelFiles())101 errs := validator.Errors()102 require.Equal(t, 2, len(errs), "%v", errs)103 // These two may come back in different order.104 assert.True(t, strings.Contains(errs[0], "custom_tag_file.txt") ||105 strings.Contains(errs[0], "junk_file.txt"))106 assert.True(t, strings.Contains(errs[1], "custom_tag_file.txt") ||107 strings.Contains(errs[1], "junk_file.txt"))108}109func TestValidateMiscDirectories(t *testing.T) {110 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")111 require.NotNil(t, validator)112 validator.Profile.AllowMiscDirectories = true113 validator.ReadBag()114 assert.True(t, validator.ValidateMiscDirectories())115 assert.Empty(t, validator.Errors())116 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")117 require.NotNil(t, validator)118 validator.Profile.AllowMiscDirectories = false119 validator.ReadBag()120 assert.False(t, validator.ValidateMiscDirectories())121 require.NotEmpty(t, validator.Errors())122 assert.Equal(t, "Directory 'custom_tags' is not allowed in top-level directory when BagIt profile says AllowMiscDirectories is false.", validator.Errors()[0])123}124func TestValidateBagItVersion(t *testing.T) {125 // Both profile and bag say version 0.97126 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")127 require.NotNil(t, validator)128 validator.ReadBag()129 assert.True(t, validator.ValidateBagItVersion())130 assert.Empty(t, validator.Errors())131 // If no accepted versions are specified, then any version will do.132 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")133 require.NotNil(t, validator)134 validator.Profile.AcceptBagItVersion = nil135 validator.ReadBag()136 assert.True(t, validator.ValidateBagItVersion())137 assert.Empty(t, validator.Errors())138 // Mismatch between accepted versions and actual version should139 // cause a validation error.140 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")141 require.NotNil(t, validator)142 validator.Profile.AcceptBagItVersion = []string{"2.22", "3.33", "4.44"}143 validator.ReadBag()144 assert.False(t, validator.ValidateBagItVersion())145 require.Equal(t, 1, len(validator.Errors()))146 assert.Equal(t, "BagIt version 0.97 in bagit.txt does not match allowed version(s) 2.22,3.33,4.44", validator.Errors()[0])147 // Be specific about missing BagIt version148 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")149 require.NotNil(t, validator)150 validator.ReadBag()151 validator.Bag.TagFiles["bagit.txt"].ParsedData.DeleteByKey("BagIt-Version")152 assert.False(t, validator.ValidateBagItVersion())153 require.Equal(t, 1, len(validator.Errors()))154 assert.Equal(t, "Profile requires a specific BagIt version, but no version is specified in bagit.txt", validator.Errors()[0])155}156func TestValidateAllowFetch(t *testing.T) {157 // fetch.txt not allowed and not present158 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")159 require.NotNil(t, validator)160 validator.Profile.AllowFetchTxt = false161 assert.True(t, validator.ValidateAllowFetch())162 assert.Empty(t, validator.Errors())163 // Not allowed and present164 validator.Bag.TagFiles["fetch.txt"] = &bagit.File{}165 assert.False(t, validator.ValidateAllowFetch())166 require.NotEmpty(t, validator.Errors())167 assert.Equal(t, "Found fetch.txt, which BagIt profile says is not allowed.", validator.Errors()[0])168 // Allowed, but not present169 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")170 require.NotNil(t, validator)171 validator.Profile.AllowFetchTxt = true172 assert.True(t, validator.ValidateAllowFetch())173 assert.Empty(t, validator.Errors())174 // Alloed and present175 validator.Bag.TagFiles["fetch.txt"] = &bagit.File{}176 assert.True(t, validator.ValidateAllowFetch())177 assert.Empty(t, validator.Errors())178}179func TestValidateSerialization(t *testing.T) {180 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")181 require.NotNil(t, validator)182 assert.True(t, validator.ValidateSerialization())183 assert.Empty(t, validator.Errors())184 validator.Profile.Serialization = constants.REQUIRED185 assert.True(t, validator.ValidateSerialization())186 assert.Empty(t, validator.Errors())187 validator.Profile.Serialization = constants.OPTIONAL188 assert.True(t, validator.ValidateSerialization())189 assert.Empty(t, validator.Errors())190 validator.Profile.Serialization = constants.FORBIDDEN191 assert.False(t, validator.ValidateSerialization())192 require.NotEmpty(t, validator.Errors())193 assert.Equal(t, "Serialization is forbidden, but bag is a single file", validator.Errors()[0])194}195func TestValidateSerializationFormat(t *testing.T) {196 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")197 require.NotNil(t, validator)198 // OK because profile says serialization is required199 // and we accept tar format.200 assert.True(t, validator.ValidateSerializationFormat())201 assert.Empty(t, validator.Errors())202 // Should fail, because the list of accepted formats203 // does not include .tar204 validator.Profile.AcceptSerialization = []string{".rar", ".7z", "zip"}205 assert.False(t, validator.ValidateSerializationFormat())206 require.NotEmpty(t, validator.Errors())207 assert.Equal(t, "Serialization format .tar is not in the Accept-Serialization list for this BagIt profile.", validator.Errors()[0])208 // Unrecognized format209 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")210 require.NotNil(t, validator)211 validator.Bag.Path = "path/to/unknown/format.fake"212 assert.False(t, validator.ValidateSerializationFormat())213 require.NotEmpty(t, validator.Errors())214 assert.Equal(t, "Unknown serialization type for format .fake.", validator.Errors()[0])215 // No serialization types specified in profile216 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")217 require.NotNil(t, validator)218 validator.Profile.AcceptSerialization = nil219 assert.False(t, validator.ValidateSerializationFormat())220 require.NotEmpty(t, validator.Errors())221 assert.Equal(t, "Bag is serialized, but profile does not specify accepted serializations.", validator.Errors()[0])222}223func TestValidateRequiredManifests(t *testing.T) {224 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")225 require.NotNil(t, validator)226 assert.True(t, validator.ValidateRequiredManifests())227 assert.Empty(t, validator.Errors())228 validator.Profile.ManifestsRequired = append(validator.Profile.ManifestsRequired, "sha512")229 assert.False(t, validator.ValidateRequiredManifests())230 assert.NotEmpty(t, validator.Errors())231 assert.Equal(t, "Required manifest 'manifest-sha512.txt' is missing.", validator.Errors()[0])232 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")233 validator.Profile.TagManifestsRequired = append(validator.Profile.TagManifestsRequired, "sha512")234 assert.False(t, validator.ValidateRequiredManifests())235 assert.NotEmpty(t, validator.Errors())236 assert.Equal(t, "Required tag manifest 'tagmanifest-sha512.txt' is missing.", validator.Errors()[0])237}238func TestValidateTagFiles(t *testing.T) {239 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")240 require.NotNil(t, validator)241 assert.True(t, validator.ValidateTagFiles())242 assert.Empty(t, validator.Errors())243 // Make sure it catches missing files.244 delete(validator.Bag.TagFiles, "aptrust-info.txt")245 assert.False(t, validator.ValidateTagFiles())246 require.NotEmpty(t, validator.Errors())247 assert.Equal(t, "Required tag file 'aptrust-info.txt' is missing.", validator.Errors()[0])248 // Make sure it catches missing tags.249 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")250 require.NotNil(t, validator)251 validator.ReadBag()252 validator.Bag.TagFiles["aptrust-info.txt"].ParsedData.DeleteByKey("Title")253 assert.False(t, validator.ValidateTagFiles())254 require.NotEmpty(t, validator.Errors())255 assert.Equal(t, "Required tag 'Title' is missing from file 'aptrust-info.txt'.", validator.Errors()[0])256}257func TestValidateTag(t *testing.T) {258 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")259 require.NotNil(t, validator)260 tagDef := validator.Profile.FindTagDef("aptrust-info.txt", "Access")261 assert.True(t, validator.ValidateTag(tagDef, []string{"Consortia"}))262 assert.Empty(t, validator.Errors())263 assert.True(t, validator.ValidateTag(tagDef, []string{"Institution"}))264 assert.Empty(t, validator.Errors())265 assert.True(t, validator.ValidateTag(tagDef, []string{"Restricted"}))266 assert.Empty(t, validator.Errors())267 // Value not explicitly allowed268 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")269 require.NotNil(t, validator)270 assert.False(t, validator.ValidateTag(tagDef, []string{"Inertia"}))271 require.NotEmpty(t, validator.Errors())272 assert.Equal(t, "In file 'aptrust-info.txt': Value 'Inertia' for tag 'Access' is not in list of allowed values (Consortia, Institution, Restricted)", validator.Errors()[0])273 // Missing required tag274 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")275 require.NotNil(t, validator)276 assert.False(t, validator.ValidateTag(tagDef, nil))277 require.NotEmpty(t, validator.Errors())278 assert.Equal(t, "Required tag 'Access' is missing from file 'aptrust-info.txt'.", validator.Errors()[0])279 // Empty tag where empty is not OK280 validator = getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")281 require.NotNil(t, validator)282 assert.False(t, validator.ValidateTag(tagDef, []string{"", "", ""}))283 require.NotEmpty(t, validator.Errors())284 assert.Equal(t, "Tag 'Access' in file 'aptrust-info.txt' cannot be empty.", validator.Errors()[0])285}286func TestValidateChecksums(t *testing.T) {287 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")288 require.NotNil(t, validator)289 assert.True(t, validator.ValidateChecksums())290 assert.Empty(t, validator.Errors())291}292// ---------- Test specific bags with specific issues --------- //293func TestValidateBadAccessBag(t *testing.T) {294 validator := getValidator(t, "example.edu.sample_bad_access.tar", "aptrust_bagit_profile_2.1.json")295 require.NotNil(t, validator)296 assert.False(t, validator.Validate())297 errors := validator.Errors()298 assert.Equal(t, 1, len(errors))299 assert.True(t, util.StringListContains(errors, "In file 'aptrust-info.txt': Value 'Hands Off!' for tag 'Access' is not in list of allowed values (Consortia, Institution, Restricted)"))300}301func TestValidateBadChecksumsBag(t *testing.T) {302 validator := getValidator(t, "example.edu.sample_bad_checksums.tar", "aptrust_bagit_profile_2.1.json")303 require.NotNil(t, validator)304 assert.False(t, validator.Validate())305 errors := validator.Errors()306 require.NotEmpty(t, errors)307 expected := []string{308 "Required tag 'Access' is missing from file 'aptrust-info.txt'.",309 "Digest for data/datastream-DC in manifest manifest-md5.txt: '44d85cf4810d6c6fe877BlahBlahBlah' does not match actual '44d85cf4810d6c6fe87750117633e461'",310 "Digest for data/datastream-descMetadata in manifest manifest-md5.txt: '4bd0ad5f85c00ce84a45BlahBlahBlah' does not match actual '4bd0ad5f85c00ce84a455466b24c8960'",311 "Digest for data/datastream-MARC in manifest manifest-md5.txt: '93e381dfa9ad0086dbe3BlahBlahBlah' does not match actual '93e381dfa9ad0086dbe3b92e0324bae6'",312 "Digest for data/datastream-RELS-EXT in manifest manifest-md5.txt: 'ff731b9a1758618f6cc2BlahBlahBlah' does not match actual 'ff731b9a1758618f6cc22538dede6174'",313 }314 for _, msg := range expected {315 assert.True(t, util.StringListContains(errors, msg), "Missing expected error: %s", msg)316 }317}318func TestValidateGoodBag(t *testing.T) {319 validator := getValidator(t, "example.edu.sample_good.tar", "aptrust_bagit_profile_2.1.json")320 require.NotNil(t, validator)321 assert.True(t, validator.Validate())322 errors := validator.Errors()323 require.Empty(t, errors)324}325func TestValidateMissingDataFileBag(t *testing.T) {326 validator := getValidator(t, "example.edu.sample_missing_data_file.tar", "aptrust_bagit_profile_2.1.json")327 require.NotNil(t, validator)328 assert.False(t, validator.Validate())329 errors := validator.Errors()330 require.Equal(t, 2, len(errors))331 expected := []string{332 "Required tag 'Access' is missing from file 'aptrust-info.txt'.",333 "File data/datastream-DC in manifest manifest-md5.txt is missing from the data directory",334 }335 for _, msg := range expected {336 assert.True(t, util.StringListContains(errors, msg), "Missing expected error: %s", msg)337 }338}339func TestValidateMissingAPTrustInfoBag(t *testing.T) {340 validator := getValidator(t, "example.edu.sample_no_aptrust_info.tar", "aptrust_bagit_profile_2.1.json")341 require.NotNil(t, validator)342 assert.False(t, validator.Validate())343 errors := validator.Errors()344 require.Equal(t, 1, len(errors))345 assert.Equal(t, "Required tag file 'aptrust-info.txt' is missing.", errors[0])346}347func TestValidateNoBagInfoBag(t *testing.T) {348 validator := getValidator(t, "example.edu.sample_no_bag_info.tar", "aptrust_bagit_profile_2.1.json")349 require.NotNil(t, validator)350 assert.False(t, validator.Validate())351 errors := validator.Errors()352 require.Equal(t, 2, len(errors))353 expected := []string{354 "Required tag file 'bag-info.txt' is missing.",355 "Required tag 'Access' is missing from file 'aptrust-info.txt'.",356 }357 for _, msg := range expected {358 assert.True(t, util.StringListContains(errors, msg), "Missing expected error: %s", msg)359 }360}361func TestValidateNoBagItBag(t *testing.T) {362 validator := getValidator(t, "example.edu.sample_no_bagit.tar", "aptrust_bagit_profile_2.1.json")363 require.NotNil(t, validator)364 assert.False(t, validator.Validate())365 errors := validator.Errors()366 require.Equal(t, 3, len(errors))367 expected := []string{368 "Cannot check bagit version because bagit.txt is missing.",369 "Required tag file 'bagit.txt' is missing.",370 "Required tag 'Access' is missing from file 'aptrust-info.txt'.",371 }372 for _, msg := range expected {373 assert.True(t, util.StringListContains(errors, msg), "Missing expected error: %s", msg)374 }375}376func TestValidateNoDataDirBag(t *testing.T) {377 validator := getValidator(t, "example.edu.sample_no_data_dir.tar", "aptrust_bagit_profile_2.1.json")378 require.NotNil(t, validator)379 assert.False(t, validator.Validate())380 errors := validator.Errors()381 assert.Equal(t, 4, len(errors))382 expected := []string{383 "File data/datastream-DC in manifest manifest-md5.txt is missing from the data directory",384 "File data/datastream-descMetadata in manifest manifest-md5.txt is missing from the data directory",385 "File data/datastream-MARC in manifest manifest-md5.txt is missing from the data directory",386 "File data/datastream-RELS-EXT in manifest manifest-md5.txt is missing from the data directory",387 }388 for _, msg := range expected {389 assert.True(t, util.StringListContains(errors, msg), "Missing expected error: %s", msg)390 }391}392func TestValidateNoMd5ManifestBag(t *testing.T) {393 validator := getValidator(t, "example.edu.sample_no_md5_manifest.tar", "aptrust_bagit_profile_2.1.json")394 require.NotNil(t, validator)395 assert.False(t, validator.Validate())396 errors := validator.Errors()397 require.Equal(t, 1, len(errors))398 assert.Equal(t, "Required manifest 'manifest-md5.txt' is missing.", errors[0])399}400func TestValidateNoTitleBag(t *testing.T) {401 validator := getValidator(t, "example.edu.sample_no_title.tar", "aptrust_bagit_profile_2.1.json")402 require.NotNil(t, validator)403 assert.False(t, validator.Validate())404 errors := validator.Errors()405 require.Equal(t, 1, len(errors))406 assert.Equal(t, "Tag 'Title' in file 'aptrust-info.txt' cannot be empty.", errors[0])407}408func TestValidateWrongFolderNameBag(t *testing.T) {409 validator := getValidator(t, "example.edu.sample_wrong_folder_name.tar", "aptrust_bagit_profile_2.1.json")410 require.NotNil(t, validator)411 assert.False(t, validator.Validate())412 errors := validator.Errors()413 require.Equal(t, 1, len(errors))414 assert.Equal(t, "Bag should untar to a single directory whose name matches the name of the tar file", errors[0])415}416func TestValidateBadTagSampleBag(t *testing.T) {417 validator := getValidator(t, "example.edu.tagsample_bad.tar", "aptrust_bagit_profile_2.1.json")418 require.NotNil(t, validator)419 assert.False(t, validator.Validate())420 errors := validator.Errors()421 require.NotEmpty(t, errors)422 assert.Equal(t, 6, len(errors))423 expected := []string{424 "Tag 'Title' in file 'aptrust-info.txt' cannot be empty.",425 "In file 'aptrust-info.txt': Value 'acksess' for tag 'Access' is not in list of allowed values (Consortia, Institution, Restricted)",426 "Digest for data/datastream-descMetadata in manifest manifest-sha256.txt: 'This-checksum-is-bad-on-purpose.-The-validator-should-catch-it!!' does not match actual 'cf9cbce80062932e10ee9cd70ec05ebc24019deddfea4e54b8788decd28b4bc7'",427 "File data/file-not-in-bag in manifest manifest-sha256.txt is missing from the data directory",428 "Digest for custom_tags/tracked_tag_file.txt in tag manifest tagmanifest-sha256.txt: '0000000000000000000000000000000000000000000000000000000000000000' does not match actual '3f2f50c5bde87b58d6132faee14d1a295d115338643c658df7fa147e2296ccdd'",429 "Digest for custom_tags/tracked_tag_file.txt in tag manifest tagmanifest-md5.txt: '00000000000000000000000000000000' does not match actual 'dafbffffc3ed28ef18363394935a2651'",430 }431 for _, msg := range expected {432 assert.True(t, util.StringListContains(errors, msg), "Missing expected error: %s", msg)433 }434}435func TestValidateGoodTagSampleBag(t *testing.T) {436 validator := getValidator(t, "example.edu.tagsample_good.tar", "aptrust_bagit_profile_2.1.json")437 require.NotNil(t, validator)438 assert.True(t, validator.Validate())439 assert.Empty(t, validator.Errors())440}441// Bag example.edu.tagsample_good.tar is valid according to the APTrust442// BagIt profile, but not valid according to the DPN profile. So although443// it passed in the test above, it should fail here.444func TestValidateAPTrustBagUsingDPNProfile(t *testing.T) {445 validator := getValidator(t, "example.edu.tagsample_good.tar", "dpn_bagit_profile_2.1.json")446 require.NotNil(t, validator)447 assert.False(t, validator.Validate())448 errors := validator.Errors()449 require.NotEmpty(t, errors)450 assert.Equal(t, 9, len(errors), "%v", errors)451 expected := []string{452 "Non-manifest file 'aptrust-info.txt' is not allowed in top-level directory when BagIt profile says AllowMiscTopLevelFiles is false.",453 "Non-manifest file 'custom_tag_file.txt' is not allowed in top-level directory when BagIt profile says AllowMiscTopLevelFiles is false.",454 "Non-manifest file 'junk_file.txt' is not allowed in top-level directory when BagIt profile says AllowMiscTopLevelFiles is false.",455 "Required tag 'Organization-Address' is missing from file 'bag-info.txt'.",456 "Required tag 'Contact-Name' is missing from file 'bag-info.txt'.",457 "Required tag 'Contact-Phone' is missing from file 'bag-info.txt'.",458 "Required tag 'Contact-Email' is missing from file 'bag-info.txt'.",459 "Required tag 'Bag-Size' is missing from file 'bag-info.txt'.",...
validator.go
Source:validator.go
...38 }39 }40 contr := bc.GetContract()41 now := time.Now()42 if err = contr.Call(co, &results, "getValidator", validatorID); err != nil {43 _, err2 := bc.RawCall(ctx, co, "getValidator", validatorID)44 if err2 == transport.ErrEmptyResponse {45 rawRequestDuration.WithLabels("getValidator", "empty").Observe(time.Since(now).Seconds())46 return v, err247 }48 rawRequestDuration.WithLabels("getValidator", "err").Observe(time.Since(now).Seconds())49 return v, fmt.Errorf("error calling getValidator %w ", err)50 }51 rawRequestDuration.WithLabels("getValidator", "ok").Observe(time.Since(now).Seconds())52 if len(results) == 0 {53 return v, errors.New("empty result")54 }55 vr := &ValidatorRaw{}56 vraw := *abi.ConvertType(results[0], vr).(*ValidatorRaw)57 return structs.Validator{58 ValidatorID: new(big.Int).Set(validatorID),59 Name: vraw.Name,60 ValidatorAddress: vraw.ValidatorAddress,61 RequestedAddress: vraw.RequestedAddress,62 Description: vraw.Description,63 FeeRate: vraw.FeeRate,64 RegistrationTime: time.Unix(vraw.RegistrationTime.Int64(), 0),65 MinimumDelegationAmount: vraw.MinimumDelegationAmount,66 AcceptNewRequests: vraw.AcceptNewRequests,67 }, nil68}69func (c *Caller) IsAuthorizedValidator(ctx context.Context, bc *bind.BoundContract, blockNumber uint64, validatorID *big.Int) (isAuthorized bool, err error) {70 ctxT, cancel := context.WithTimeout(ctx, time.Second*30)71 defer cancel()72 results := []interface{}{}73 co := &bind.CallOpts{74 Context: ctxT,75 }76 if c.NodeType == ENTArchive {77 if blockNumber > 0 { // (lukanus): 0 = latest78 co.BlockNumber = new(big.Int).SetUint64(blockNumber)79 } else {80 co.Pending = true81 }82 }83 now := time.Now()84 if err = bc.Call(co, &results, "isAuthorizedValidator", validatorID); err != nil {85 rawRequestDuration.WithLabels("isAuthorizedValidator", "error").Observe(time.Since(now).Seconds())86 return false, fmt.Errorf("error calling getValidator function %w", err)87 }88 rawRequestDuration.WithLabels("getValidator", "ok").Observe(time.Since(now).Seconds())89 var ok bool90 isAuthorized, ok = results[0].(bool)91 if !ok {92 return false, errors.New("earned is not bool type ")93 }94 return isAuthorized, nil95}96func (c *Caller) GetValidatorWithInfo(ctx context.Context, bc transport.BoundContractCaller, blockNumber uint64, validatorID *big.Int) (v structs.Validator, err error) {97 validator, err := c.GetValidator(ctx, bc, blockNumber, validatorID)98 if err != nil {99 return validator, err100 }101 validator.Authorized, err = c.IsAuthorizedValidator(ctx, bc.GetContract(), blockNumber, validatorID)102 if err != nil {...
fabric.go
Source:fabric.go
1package validate2import (3 "os"4 "go.avito.ru/gl/core/config"5 log "go.avito.ru/gl/core/logger"6)7//Fabric ÐаÑÑÑÐ°Ð¸Ð²Ð°ÐµÐ¼Ð°Ñ ÑабÑика, коÑоÑÐ°Ñ Ð²ÑдаÑÑ Ð²Ð°Ð»Ð¸Ð´Ð°ÑÐ¾Ñ Ð¿Ð¾ алиаÑÑ(Ð¸Ð¼Ñ Ñайла без .json)8//на даннÑй Ð¼Ð¾Ð¼ÐµÐ½Ñ Ð¼Ð¾Ð¶ÐµÑ Ð²ÑдаваÑÑ Ð»Ð¸Ð±Ð¾ json валидаÑоÑÑ, либо пÑÑÑÑÑки9//пÑÑÑ Ð´Ð¾ ÑÑ
ем задаÑÑÑÑ Ð¸Ð»Ð¸ в конÑиге или в паÑамеÑÑаÑ
конÑÑÑÑкÑоÑа10type Fabric struct {11 jsonFabric *JsonFabric12 dummyFabric *DummyFabric13 useDummy bool14}15//GetValidator возвÑаÑÐµÑ Ð²Ð°Ð»Ð¸Ð´Ð°ÑÐ¾Ñ Ð¸ оÑибкÑ(еÑли валидаÑоÑа Ð½ÐµÑ Ð¸Ð»Ð¸ пÑи его Ñоздании она бÑла)16func (f *Fabric) GetValidator(alias string) (Validator, error) {17 if f.useDummy == false {18 return f.jsonFabric.GetValidator(alias)19 }20 return f.dummyFabric.GetValidator(alias)21}22//SetUseDummy возвÑаÑаÑÑ Ð»Ð¸ ÑолÑко валидаÑоÑÑ Ð¿ÑÑÑÑÑки23func (f *Fabric) SetUseDummy(use bool) {24 f.useDummy = use25}26//NewValidateFabric ÑоздаÑÑÑÑ Ð½Ð¾Ð²Ð°Ñ ÑабÑика коÑоÑÐ°Ñ Ð±ÐµÑÐµÑ Ð¿ÑÑÑ Ð´Ð¾ ÑÑ
ем из конÑига27func NewValidateFabric(useDummy bool) *Fabric {28 cfg := &config.BaseConfig{}29 err := config.LoadFromFile(os.Getenv("CONFIG_PATH"), cfg)30 if err != nil {31 log.Fatalf("Config error: %v", err)32 }33 log.Infof("Try to create validator for jsonschema path='%s'", cfg.Validator.Path)34 return &Fabric{35 jsonFabric: NewJsonFabric(cfg.Validator.Path),36 dummyFabric: NewDummyFabric(),37 useDummy: useDummy,38 }39}40//NewValidateFabricByPath ÑоздаÑÑÑÑ Ð½Ð¾Ð²Ð°Ñ ÑабÑика коÑоÑÐ°Ñ Ð±ÐµÑÐµÑ Ð¿ÑÑÑ Ð´Ð¾ ÑÑ
ем из паÑемеÑÑа41func NewValidateFabricByPath(path string, useDummy bool) *Fabric {42 log.Infof("Try to create validator for jsonschema path='%s'", path)43 return &Fabric{44 jsonFabric: NewJsonFabric(path),45 dummyFabric: NewDummyFabric(),46 useDummy: useDummy,47 }48}...
getValidator
Using AI Code Generation
1import (2type User struct {3}4func main() {5 user := User{6 }7 validator, _ := json.GetValidator()8 err := validator.Struct(user)9 if err != nil {10 fmt.Println(err)11 }12}13import (14type User struct {15}16func main() {17 user := User{18 }19 validator, _ := json.GetValidator()20 err := validator.Struct(user)21 if err != nil {22 fmt.Println(err)23 }24}25import (26type User struct {27}28func main() {29 user := User{30 }31 validator, _ := json.GetValidator()32 err := validator.Struct(user)33 if err != nil {34 fmt.Println(err)35 }36}37import (38type User struct {39}40func main() {41 user := User{42 }
getValidator
Using AI Code Generation
1func main() {2 if err != nil {3 panic(err)4 }5 result, err := v.Validate(bytes.NewReader([]byte(`{"foo": "bar"}`)))6 if err != nil {7 panic(err)8 }9 if result.Valid() {10 fmt.Println("The document is valid")11 } else {12 fmt.Println("The document is not valid. See errors :")13 for _, desc := range result.Errors() {14 fmt.Printf("- %s15 }16 }17}
getValidator
Using AI Code Generation
1func main() {2 var json = require("json");3 var validator = json.getValidator({4 "address": {5 }6 });7 var data = {8 "address": {9 }10 };11 var result = validator.validate(data);12 if (result.isValid) {13 print("data is valid");14 } else {15 print("data is invalid");16 }17}
getValidator
Using AI Code Generation
1import (2func main() {3 jsonStr := `{"name": "John", "age": 20, "friends": ["Bob", "Alice"]}`4 var data interface{}5 err := json.Unmarshal([]byte(jsonStr), &data)6 if err != nil {7 panic(err)8 }9 validator := json.Valid([]byte(jsonStr))10}11map[string]interface {}12import (13func main() {14 jsonStr := `{"name": "John", "age": 20, "friends": ["Bob", "Alice"]}`15 var data interface{}16 err := json.Unmarshal([]byte(jsonStr), &data)17 if err != nil {18 panic(err)19 }20 validator := json.Valid([]byte(jsonStr))21 jsonStr = `{"name": "John", "age": 20, "friends": ["Bob", "Alice"]`22 validator = json.Valid([]byte(jsonStr))23}24map[string]interface {}
getValidator
Using AI Code Generation
1import (2func main() {3 slice := []int{1, 2, 3}4 validator := json.GetValidator(slice)5 fmt.Println(validator)6}
getValidator
Using AI Code Generation
1import (2func main() {3 jsonStr := `{"name":"John", "age":30}`4 var jsonData map[string]interface{}5 json.Unmarshal([]byte(jsonStr), &jsonData)6 validator := json.Valid([]byte(jsonStr))7 fmt.Println(validator)8}9Golang json.Valid() Method10json.Valid(data []byte) bool11import (12func main() {13 jsonStr := `{"name":"John", "age":30}`14 var jsonData map[string]interface{}15 json.Unmarshal([]byte(jsonStr), &jsonData)16 validator := json.Valid([]byte(jsonStr))17 fmt.Println(validator)18}19Golang json.Marshal() Method20json.Marshal(v interface{}) ([]byte, error)21import (22func main() {23 jsonStr := `{"name":"John", "age":30}`24 var jsonData map[string]interface{}25 json.Unmarshal([]byte(jsonStr), &jsonData)26 validator := json.Valid([]byte(jsonStr))27 fmt.Println(validator)
getValidator
Using AI Code Generation
1func main() {2 v := json.getValidator()3 result := v.validate("json string")4 println(result)5}6func main() {7 v := json.getValidator()8 result := v.validate("json string")9 println(result)10}11func main() {12 v := json.getValidator()13 result := v.validate("json string")14 println(result)15}16type Validator struct {17}18func getValidator() *Validator {19}20func (v *Validator) validate(json string) bool {21}22import (23 "github.com/justinpage/go-by-example/4-packages-and-imports/json"24func main() {25 v := json.getValidator()26 result := v.validate("json string")27 println(result)28}29import (30 "github.com/justinpage/go-by-example/4-packages-and-imports/json"31func main() {32 v := json.getValidator()
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!