How to use TestMetadata method of vcs Package

Best Syzkaller code snippet using vcs.TestMetadata

circleci.go

Source:circleci.go Github

copy

Full Screen

...277 return nil, err278 }279 return artifacts, nil280}281// ListTestMetadata fetches the build metadata for the given build282func (c *Client) ListTestMetadata(account, repo string, buildNum int) ([]*TestMetadata, error) {283 metadata := struct {284 Tests []*TestMetadata `json:"tests"`285 }{}286 err := c.request("GET", fmt.Sprintf("project/%s/%s/%d/tests", account, repo, buildNum), &metadata, nil, nil)287 if err != nil {288 return nil, err289 }290 return metadata.Tests, nil291}292// AddSSHUser adds the user associated with the API token to the list of valid293// SSH users for a build.294//295// The API token being used must be a user API token296func (c *Client) AddSSHUser(account, repo string, buildNum int) (*Build, error) {297 build := &Build{}298 err := c.request("POST", fmt.Sprintf("project/%s/%s/%d/ssh-users", account, repo, buildNum), build, nil, nil)299 if err != nil {300 return nil, err301 }302 return build, nil303}304// Build triggers a new build for the given project for the given305// project on the given branch.306// Returns the new build information307func (c *Client) Build(account, repo, branch string) (*Build, error) {308 return c.BuildOpts(account, repo, branch, nil)309}310// ParameterizedBuild triggers a new parameterized build for the given311// project on the given branch, Marshaling the struct into json and passing312// in the post body.313// Returns the new build information314func (c *Client) ParameterizedBuild(account, repo, branch string, buildParameters map[string]string) (*Build, error) {315 opts := map[string]interface{}{"build_parameters": buildParameters}316 return c.BuildOpts(account, repo, branch, opts)317}318// BuildOpts triggeres a new build for the givent project on the given319// branch, Marshaling the struct into json and passing320// in the post body.321// Returns the new build information322func (c *Client) BuildOpts(account, repo, branch string, opts map[string]interface{}) (*Build, error) {323 build := &Build{}324 err := c.request("POST", fmt.Sprintf("project/%s/%s/tree/%s", account, repo, branch), build, nil, opts)325 if err != nil {326 return nil, err327 }328 return build, nil329}330// BuildByProjectBranch triggers a build by project (this is the only way to trigger a build for project using Circle331// 2.1) by branch332//333// NOTE: this endpoint is only available in the CircleCI API v1.1. in order to call it, you must instantiate the Client334// object with the following value for BaseURL: &url.URL{Host: "circleci.com", Scheme: "https", Path: "/api/v1.1/"}335func (c *Client) BuildByProjectBranch(vcsType VcsType, account string, repo string, branch string) error {336 return c.buildProject(vcsType, account, repo, map[string]interface{}{337 "branch": branch,338 })339}340// BuildByProjectRevision triggers a build by project (this is the only way to trigger a build for project using Circle341// 2.1) by revision342//343// NOTE: this endpoint is only available in the CircleCI API v1.1. in order to call it, you must instantiate the Client344// object with the following value for BaseURL: &url.URL{Host: "circleci.com", Scheme: "https", Path: "/api/v1.1/"}345func (c *Client) BuildByProjectRevision(vcsType VcsType, account string, repo string, revision string) error {346 return c.buildProject(vcsType, account, repo, map[string]interface{}{347 "revision": revision,348 })349}350// BuildByProjectTag triggers a build by project (this is the only way to trigger a build for project using Circle 2.1)351// using a tag reference352//353// NOTE: this endpoint is only available in the CircleCI API v1.1. in order to call it, you must instantiate the Client354// object with the following value for BaseURL: &url.URL{Host: "circleci.com", Scheme: "https", Path: "/api/v1.1/"}355func (c *Client) BuildByProjectTag(vcsType VcsType, account string, repo string, tag string) error {356 return c.buildProject(vcsType, account, repo, map[string]interface{}{357 "tag": tag,358 })359}360func (c *Client) buildProject(vcsType VcsType, account string, repo string, opts map[string]interface{}) error {361 resp := &BuildByProjectResponse{}362 err := c.request("POST", fmt.Sprintf("project/%s/%s/%s/build", vcsType, account, repo), resp, nil, opts)363 if err != nil {364 return err365 }366 if resp.Status != 200 || resp.Body != "Build created" {367 return fmt.Errorf("unexpected build info in response %+v", resp)368 }369 return nil370}371// RetryBuild triggers a retry of the specified build372// Returns the new build information373func (c *Client) RetryBuild(account, repo string, buildNum int) (*Build, error) {374 build := &Build{}375 err := c.request("POST", fmt.Sprintf("project/%s/%s/%d/retry", account, repo, buildNum), build, nil, nil)376 if err != nil {377 return nil, err378 }379 return build, nil380}381// CancelBuild triggers a cancel of the specified build382// Returns the new build information383func (c *Client) CancelBuild(account, repo string, buildNum int) (*Build, error) {384 build := &Build{}385 err := c.request("POST", fmt.Sprintf("project/%s/%s/%d/cancel", account, repo, buildNum), build, nil, nil)386 if err != nil {387 return nil, err388 }389 return build, nil390}391// ClearCache clears the cache of the specified project392// Returns the status returned by CircleCI393func (c *Client) ClearCache(account, repo string) (string, error) {394 status := &struct {395 Status string `json:"status"`396 }{}397 err := c.request("DELETE", fmt.Sprintf("project/%s/%s/build-cache", account, repo), status, nil, nil)398 if err != nil {399 return "", err400 }401 return status.Status, nil402}403// AddEnvVar adds a new environment variable to the specified project404// Returns the added env var (the value will be masked)405func (c *Client) AddEnvVar(account, repo, name, value string) (*EnvVar, error) {406 envVar := &EnvVar{}407 err := c.request("POST", fmt.Sprintf("project/%s/%s/envvar", account, repo), envVar, nil, &EnvVar{Name: name, Value: value})408 if err != nil {409 return nil, err410 }411 return envVar, nil412}413// ListEnvVars list environment variable to the specified project414// Returns the env vars (the value will be masked)415func (c *Client) ListEnvVars(account, repo string) ([]EnvVar, error) {416 envVar := []EnvVar{}417 err := c.request("GET", fmt.Sprintf("project/%s/%s/envvar", account, repo), &envVar, nil, nil)418 if err != nil {419 return nil, err420 }421 return envVar, nil422}423// DeleteEnvVar deletes the specified environment variable from the project424func (c *Client) DeleteEnvVar(account, repo, name string) error {425 return c.request("DELETE", fmt.Sprintf("project/%s/%s/envvar/%s", account, repo, name), nil, nil, nil)426}427// AddSSHKey adds a new SSH key to the project428func (c *Client) AddSSHKey(account, repo, hostname, privateKey string) error {429 key := &struct {430 Hostname string `json:"hostname"`431 PrivateKey string `json:"private_key"`432 }{hostname, privateKey}433 return c.request("POST", fmt.Sprintf("project/%s/%s/ssh-key", account, repo), nil, nil, key)434}435// GetActionOutputs fetches the output for the given action436// If the action has no output, returns nil437func (c *Client) GetActionOutputs(a *Action) ([]*Output, error) {438 if !a.HasOutput || a.OutputURL == "" {439 return nil, nil440 }441 req, err := http.NewRequest("GET", a.OutputURL, nil)442 if err != nil {443 return nil, err444 }445 c.debugRequest(req)446 resp, err := c.client().Do(req)447 if err != nil {448 return nil, err449 }450 defer resp.Body.Close()451 c.debugResponse(resp)452 output := []*Output{}453 if err = json.NewDecoder(resp.Body).Decode(&output); err != nil {454 return nil, err455 }456 return output, nil457}458// ListCheckoutKeys fetches the checkout keys associated with the given project459func (c *Client) ListCheckoutKeys(account, repo string) ([]*CheckoutKey, error) {460 checkoutKeys := []*CheckoutKey{}461 err := c.request("GET", fmt.Sprintf("project/%s/%s/checkout-key", account, repo), &checkoutKeys, nil, nil)462 if err != nil {463 return nil, err464 }465 return checkoutKeys, nil466}467// CreateCheckoutKey creates a new checkout key for a project468// Valid key types are currently deploy-key and github-user-key469//470// The github-user-key type requires that the API token being used be a user API token471func (c *Client) CreateCheckoutKey(account, repo, keyType string) (*CheckoutKey, error) {472 checkoutKey := &CheckoutKey{}473 body := struct {474 KeyType string `json:"type"`475 }{KeyType: keyType}476 err := c.request("POST", fmt.Sprintf("project/%s/%s/checkout-key", account, repo), checkoutKey, nil, body)477 if err != nil {478 return nil, err479 }480 return checkoutKey, nil481}482// GetCheckoutKey fetches the checkout key for the given project by fingerprint483func (c *Client) GetCheckoutKey(account, repo, fingerprint string) (*CheckoutKey, error) {484 checkoutKey := &CheckoutKey{}485 err := c.request("GET", fmt.Sprintf("project/%s/%s/checkout-key/%s", account, repo, fingerprint), &checkoutKey, nil, nil)486 if err != nil {487 return nil, err488 }489 return checkoutKey, nil490}491// DeleteCheckoutKey fetches the checkout key for the given project by fingerprint492func (c *Client) DeleteCheckoutKey(account, repo, fingerprint string) error {493 return c.request("DELETE", fmt.Sprintf("project/%s/%s/checkout-key/%s", account, repo, fingerprint), nil, nil, nil)494}495// AddHerokuKey associates a Heroku key with the user's API token to allow496// CircleCI to deploy to Heroku on your behalf497//498// The API token being used must be a user API token499//500// NOTE: It doesn't look like there is currently a way to dissaccociate your501// Heroku key, so use with care502func (c *Client) AddHerokuKey(key string) error {503 body := struct {504 APIKey string `json:"apikey"`505 }{APIKey: key}506 return c.request("POST", "/user/heroku-key", nil, nil, body)507}508// EnvVar represents an environment variable509type EnvVar struct {510 Name string `json:"name"`511 Value string `json:"value"`512}513// Artifact represents a build artifact514type Artifact struct {515 NodeIndex int `json:"node_index"`516 Path string `json:"path"`517 PrettyPath string `json:"pretty_path"`518 URL string `json:"url"`519}520// UserProject returns the selective project information included when querying521// for a User522type UserProject struct {523 Emails string `json:"emails"`524 OnDashboard bool `json:"on_dashboard"`525}526// User represents a CircleCI user527type User struct {528 Admin bool `json:"admin"`529 AllEmails []string `json:"all_emails"`530 AvatarURL string `json:"avatar_url"`531 BasicEmailPrefs string `json:"basic_email_prefs"`532 Containers int `json:"containers"`533 CreatedAt time.Time `json:"created_at"`534 DaysLeftInTrial int `json:"days_left_in_trial"`535 GithubID int `json:"github_id"`536 GithubOauthScopes []string `json:"github_oauth_scopes"`537 GravatarID *string `json:"gravatar_id"`538 HerokuAPIKey *string `json:"heroku_api_key"`539 LastViewedChangelog time.Time `json:"last_viewed_changelog"`540 Login string `json:"login"`541 Name *string `json:"name"`542 Parallelism int `json:"parallelism"`543 Plan *string `json:"plan"`544 Projects map[string]*UserProject `json:"projects"`545 SelectedEmail *string `json:"selected_email"`546 SignInCount int `json:"sign_in_count"`547 TrialEnd time.Time `json:"trial_end"`548}549// AWSConfig represents AWS configuration for a project550type AWSConfig struct {551 AWSKeypair *AWSKeypair `json:"keypair"`552}553// AWSKeypair represents the AWS access/secret key for a project554// SecretAccessKey will be a masked value555type AWSKeypair struct {556 AccessKeyID string `json:"access_key_id"`557 SecretAccessKey string `json:"secret_access_key_id"`558}559// BuildSummary represents the subset of build information returned with a Project560type BuildSummary struct {561 AddedAt time.Time `json:"added_at"`562 BuildNum int `json:"build_num"`563 Outcome string `json:"outcome"`564 PushedAt time.Time `json:"pushed_at"`565 Status string `json:"status"`566 VCSRevision string `json:"vcs_revision"`567}568// Branch represents a repository branch569type Branch struct {570 LastSuccess *BuildSummary `json:"last_success"`571 PusherLogins []string `json:"pusher_logins"`572 RecentBuilds []*BuildSummary `json:"recent_builds"`573 RunningBuilds []*BuildSummary `json:"running_builds"`574}575// PublicSSHKey represents the public part of an SSH key associated with a project576// PrivateKey will be a masked value577type PublicSSHKey struct {578 Hostname string `json:"hostname"`579 PublicKey string `json:"public_key"`580 Fingerprint string `json:"fingerprint"`581}582// Project represents information about a project583type Project struct {584 AWSConfig AWSConfig `json:"aws"`585 Branches map[string]Branch `json:"branches"`586 CampfireNotifyPrefs *string `json:"campfire_notify_prefs"`587 CampfireRoom *string `json:"campfire_room"`588 CampfireSubdomain *string `json:"campfire_subdomain"`589 CampfireToken *string `json:"campfire_token"`590 Compile string `json:"compile"`591 DefaultBranch string `json:"default_branch"`592 Dependencies string `json:"dependencies"`593 Extra string `json:"extra"`594 FeatureFlags FeatureFlags `json:"feature_flags"`595 FlowdockAPIToken *string `json:"flowdock_api_token"`596 Followed bool `json:"followed"`597 HallNotifyPrefs *string `json:"hall_notify_prefs"`598 HallRoomAPIToken *string `json:"hall_room_api_token"`599 HasUsableKey bool `json:"has_usable_key"`600 HerokuDeployUser *string `json:"heroku_deploy_user"`601 HipchatAPIToken *string `json:"hipchat_api_token"`602 HipchatNotify *bool `json:"hipchat_notify"`603 HipchatNotifyPrefs *string `json:"hipchat_notify_prefs"`604 HipchatRoom *string `json:"hipchat_room"`605 IrcChannel *string `json:"irc_channel"`606 IrcKeyword *string `json:"irc_keyword"`607 IrcNotifyPrefs *string `json:"irc_notify_prefs"`608 IrcPassword *string `json:"irc_password"`609 IrcServer *string `json:"irc_server"`610 IrcUsername *string `json:"irc_username"`611 Parallel int `json:"parallel"`612 Reponame string `json:"reponame"`613 Setup string `json:"setup"`614 SlackAPIToken *string `json:"slack_api_token"`615 SlackChannel *string `json:"slack_channel"`616 SlackNotifyPrefs *string `json:"slack_notify_prefs"`617 SlackSubdomain *string `json:"slack_subdomain"`618 SlackWebhookURL *string `json:"slack_webhook_url"`619 SSHKeys []*PublicSSHKey `json:"ssh_keys"`620 Test string `json:"test"`621 Username string `json:"username"`622 VCSURL string `json:"vcs_url"`623}624type FeatureFlags struct {625 TrustyBeta bool `json:"trusty-beta"`626 OSX bool `json:"osx"`627 SetGithubStatus bool `json:"set-github-status"`628 BuildPRsOnly bool `json:"build-prs-only"`629 ForksReceiveSecretVars bool `json:"forks-receive-secret-env-vars"`630 Fleet *string `json:"fleet"`631 BuildForkPRs bool `json:"build-fork-prs"`632 AutocancelBuilds bool `json:"autocancel-builds"`633 OSS bool `json:"oss"`634 MemoryLimit *string `json:"memory-limit"`635 raw map[string]interface{}636}637func (f *FeatureFlags) UnmarshalJSON(b []byte) error {638 if err := json.Unmarshal(b, &f.raw); err != nil {639 return err640 }641 if v, ok := f.raw["trusty-beta"]; ok {642 f.TrustyBeta = v.(bool)643 }644 if v, ok := f.raw["osx"]; ok {645 f.OSX = v.(bool)646 }647 if v, ok := f.raw["set-github-status"]; ok {648 f.SetGithubStatus = v.(bool)649 }650 if v, ok := f.raw["build-prs-only"]; ok {651 f.BuildPRsOnly = v.(bool)652 }653 if v, ok := f.raw["forks-receive-secret-env-vars"]; ok {654 f.ForksReceiveSecretVars = v.(bool)655 }656 if v, ok := f.raw["fleet"]; ok {657 if v != nil {658 s := v.(string)659 f.Fleet = &s660 }661 }662 if v, ok := f.raw["build-fork-prs"]; ok {663 f.BuildForkPRs = v.(bool)664 }665 if v, ok := f.raw["autocancel-builds"]; ok {666 f.AutocancelBuilds = v.(bool)667 }668 if v, ok := f.raw["oss"]; ok {669 f.OSS = v.(bool)670 }671 if v, ok := f.raw["memory-limit"]; ok {672 if v != nil {673 s := v.(string)674 f.MemoryLimit = &s675 }676 }677 return nil678}679// Raw returns the underlying map[string]interface{} representing the feature flags680// This is useful to access flags that have been added to the API, but not yet added to this library681func (f *FeatureFlags) Raw() map[string]interface{} {682 return f.raw683}684// CommitDetails represents information about a commit returned with other685// structs686type CommitDetails struct {687 AuthorDate *time.Time `json:"author_date"`688 AuthorEmail string `json:"author_email"`689 AuthorLogin string `json:"author_login"`690 AuthorName string `json:"author_name"`691 Body string `json:"body"`692 Branch string `json:"branch"`693 Commit string `json:"commit"`694 CommitURL string `json:"commit_url"`695 CommitterDate *time.Time `json:"committer_date"`696 CommitterEmail string `json:"committer_email"`697 CommitterLogin string `json:"committer_login"`698 CommitterName string `json:"committer_name"`699 Subject string `json:"subject"`700}701// Message represents build messages702type Message struct {703 Message string `json:"message"`704 Type string `json:"type"`705}706// Node represents the node a build was run on707type Node struct {708 ImageID string `json:"image_id"`709 Port int `json:"port"`710 PublicIPAddr string `json:"public_ip_addr"`711 SSHEnabled *bool `json:"ssh_enabled"`712 Username string `json:"username"`713}714// CircleYML represents the serialized CircleCI YML file for a given build715type CircleYML struct {716 String string `json:"string"`717}718// BuildStatus represents status information about the build719// Used when a short summary of previous builds is included720type BuildStatus struct {721 BuildTimeMillis int `json:"build_time_millis"`722 Status string `json:"status"`723 BuildNum int `json:"build_num"`724}725// BuildUser represents the user that triggered the build726type BuildUser struct {727 Email *string `json:"email"`728 IsUser bool `json:"is_user"`729 Login string `json:"login"`730 Name *string `json:"name"`731}732// Workflow represents the details of the workflow for a build733type Workflow struct {734 JobName string `json:"job_name"`735 JobId string `json:"job_id"`736 UpstreamJobIds []*string `json:"upstream_job_ids"`737 WorkflowId string `json:"workflow_id"`738 WorkspaceId string `json:"workspace_id"`739 WorkflowName string `json:"workflow_name"`740}741// Build represents the details of a build742type Build struct {743 AllCommitDetails []*CommitDetails `json:"all_commit_details"`744 AuthorDate *time.Time `json:"author_date"`745 AuthorEmail string `json:"author_email"`746 AuthorName string `json:"author_name"`747 Body string `json:"body"`748 Branch string `json:"branch"`749 BuildNum int `json:"build_num"`750 BuildParameters map[string]string `json:"build_parameters"`751 BuildTimeMillis *int `json:"build_time_millis"`752 BuildURL string `json:"build_url"`753 Canceled bool `json:"canceled"`754 CircleYML *CircleYML `json:"circle_yml"`755 CommitterDate *time.Time `json:"committer_date"`756 CommitterEmail string `json:"committer_email"`757 CommitterName string `json:"committer_name"`758 Compare *string `json:"compare"`759 DontBuild *string `json:"dont_build"`760 Failed *bool `json:"failed"`761 FeatureFlags map[string]string `json:"feature_flags"`762 InfrastructureFail bool `json:"infrastructure_fail"`763 IsFirstGreenBuild bool `json:"is_first_green_build"`764 JobName *string `json:"job_name"`765 Lifecycle string `json:"lifecycle"`766 Messages []*Message `json:"messages"`767 Node []*Node `json:"node"`768 OSS bool `json:"oss"`769 Outcome string `json:"outcome"`770 Parallel int `json:"parallel"`771 Picard *Picard `json:"picard"`772 Platform string `json:"platform"`773 Previous *BuildStatus `json:"previous"`774 PreviousSuccessfulBuild *BuildStatus `json:"previous_successful_build"`775 PullRequests []*PullRequest `json:"pull_requests"`776 QueuedAt string `json:"queued_at"`777 Reponame string `json:"reponame"`778 Retries []int `json:"retries"`779 RetryOf *int `json:"retry_of"`780 SSHEnabled *bool `json:"ssh_enabled"`781 SSHUsers []*SSHUser `json:"ssh_users"`782 StartTime *time.Time `json:"start_time"`783 Status string `json:"status"`784 Steps []*Step `json:"steps"`785 StopTime *time.Time `json:"stop_time"`786 Subject string `json:"subject"`787 Timedout bool `json:"timedout"`788 UsageQueuedAt string `json:"usage_queued_at"`789 User *BuildUser `json:"user"`790 Username string `json:"username"`791 VcsRevision string `json:"vcs_revision"`792 VcsTag string `json:"vcs_tag"`793 VCSURL string `json:"vcs_url"`794 Workflows *Workflow `json:"workflows"`795 Why string `json:"why"`796}797// Picard represents metadata about an execution environment798type Picard struct {799 BuildAgent *BuildAgent `json:"build_agent"`800 ResourceClass *ResourceClass `json:"resource_class"`801 Executor string `json:"executor"`802}803// PullRequest represents a pull request804type PullRequest struct {805 HeadSha string `json:"head_sha"`806 URL string `json:"url"`807}808// ResourceClass represents usable resource information for a job809type ResourceClass struct {810 CPU float64 `json:"cpu"`811 RAM int `json:"ram"`812 Class string `json:"class"`813}814// BuildAgent represents an agent's information815type BuildAgent struct {816 Image *string `json:"image"`817 Properties *BuildAgentProperties `json:"properties"`818}819// BuildAgentProperties represents agent properties820type BuildAgentProperties struct {821 BuildAgent string `json:"image"`822 Executor string `json:"executor"`823}824// Step represents an individual step in a build825// Will contain more than one action if the step was parallelized826type Step struct {827 Name string `json:"name"`828 Actions []*Action `json:"actions"`829}830// Action represents an individual action within a build step831type Action struct {832 Background bool `json:"background"`833 BashCommand *string `json:"bash_command"`834 Canceled *bool `json:"canceled"`835 Continue *string `json:"continue"`836 EndTime *time.Time `json:"end_time"`837 ExitCode *int `json:"exit_code"`838 Failed *bool `json:"failed"`839 HasOutput bool `json:"has_output"`840 Index int `json:"index"`841 InfrastructureFail *bool `json:"infrastructure_fail"`842 Messages []string `json:"messages"`843 Name string `json:"name"`844 OutputURL string `json:"output_url"`845 Parallel bool `json:"parallel"`846 RunTimeMillis int `json:"run_time_millis"`847 StartTime *time.Time `json:"start_time"`848 Status string `json:"status"`849 Step int `json:"step"`850 Timedout *bool `json:"timedout"`851 Truncated bool `json:"truncated"`852 Type string `json:"type"`853}854// TestMetadata represents metadata collected from the test run (e.g. JUnit output)855type TestMetadata struct {856 Classname string `json:"classname"`857 File string `json:"file"`858 Message *string `json:"message"`859 Name string `json:"name"`860 Result string `json:"result"`861 RunTime float64 `json:"run_time"`862 Source string `json:"source"`863 SourceType string `json:"source_type"`864}865// Output represents the output of a given action866type Output struct {867 Type string `json:"type"`868 Time time.Time `json:"time"`869 Message string `json:"message"`...

Full Screen

Full Screen

contents_test.go

Source:contents_test.go Github

copy

Full Screen

1/*2Copyright SecureKey Technologies Inc. All Rights Reserved.3SPDX-License-Identifier: Apache-2.04*/5package wallet6import (7 "errors"8 "fmt"9 "testing"10 "time"11 "github.com/google/uuid"12 "github.com/stretchr/testify/require"13 "github.com/hyperledger/aries-framework-go/component/storage/edv"14 vdrapi "github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr"15 mockkms "github.com/hyperledger/aries-framework-go/pkg/mock/kms"16 mockstorage "github.com/hyperledger/aries-framework-go/pkg/mock/storage"17 "github.com/hyperledger/aries-framework-go/pkg/mock/vdr"18 "github.com/hyperledger/aries-framework-go/spi/storage"19)20const (21 sampleContenttErr = "sample content err"22 sampleContentValid = `{23 "@context": ["https://w3id.org/wallet/v1"],24 "id": "did:example:123456789abcdefghi",25 "type": "Person",26 "name": "John Smith",27 "image": "https://via.placeholder.com/150",28 "description" : "Professional software developer for Acme Corp.",29 "tags": ["professional", "person"],30 "correlation": ["4058a72a-9523-11ea-bb37-0242ac130002"]31 }`32 sampleContentNoID = `{33 "@context": ["https://w3id.org/wallet/v1"],34 "type": "Person",35 "name": "John Smith",36 "image": "https://via.placeholder.com/150",37 "description" : "Professional software developer for Acme Corp.",38 "tags": ["professional", "person"],39 "correlation": ["4058a72a-9523-11ea-bb37-0242ac130002"]40 }`41 sampleContentInvalid = `{42 "@context": ["https://w3id.org/wallet/v1"],43 "type": "Person",44 "name": "John Smith",45 "image": "https://via.placeholder.com/150",46 "description" : "Professional software developer for Acme Corp.",47 "tags": ["professional", "person"],48 "correlation": ["4058a72a-9523-11ea-bb37-0242ac130002"]49 }`50 didResolutionResult = `{51 "@context": [52 "https://w3id.org/wallet/v1",53 "https://w3id.org/did-resolution/v1"54 ],55 "id": "did:example:123",56 "type": ["DIDResolutionResponse"],57 "name": "Farming Sensor DID Document",58 "image": "https://via.placeholder.com/150",59 "description": "An IoT device in the middle of a corn field.",60 "tags": ["professional"],61 "correlation": ["4058a72a-9523-11ea-bb37-0242ac130002"],62 "created": "2017-06-18T21:19:10Z",63 "expires": "2026-06-18T21:19:10Z",64 "didDocument": {65 "@context": [66 "https://www.w3.org/ns/did/v1",67 {68 "@base": "did:key:z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg"69 }70 ],71 "id": "did:key:z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg",72 "verificationMethod": [73 {74 "id": "#z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg",75 "type": "JsonWebKey2020",76 "controller": "did:key:z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg",77 "publicKeyJwk": {78 "crv": "Ed25519",79 "x": "vGur-MEOrN6GDLf4TBGHDYAERxkmWOjTbztvG3xP0I8",80 "kty": "OKP"81 }82 },83 {84 "id": "#z6LScrLMVd9jvbphPeQkGffSeB99EWSYqAnMg8rGiHCgz5ha",85 "type": "JsonWebKey2020",86 "controller": "did:key:z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg",87 "publicKeyJwk": {88 "kty": "OKP",89 "crv": "X25519",90 "x": "EXXinkMxdA4zGmwpOOpbCXt6Ts6CwyXyEKI3jfHkS3k"91 }92 }93 ],94 "authentication": [95 "#z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg"96 ],97 "assertionMethod": [98 "#z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg"99 ],100 "capabilityInvocation": [101 "#z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg"102 ],103 "capabilityDelegation": [104 "#z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg"105 ],106 "keyAgreement": [107 "#z6LScrLMVd9jvbphPeQkGffSeB99EWSYqAnMg8rGiHCgz5ha"108 ]109 },110 "didDocumentMetadata": {111 "content-type": "application/did+json"112 },113 "didResolutionMetadata": {}114 }`115 sampleKeyContentBase58Valid = `{116 "@context": ["https://w3id.org/wallet/v1"],117 "id": "did:example:123456789abcdefghi#key-1",118 "controller": "did:example:123456789abcdefghi",119 "type": "Ed25519VerificationKey2018",120 "privateKeyBase58":"zJRjGFZydU5DBdS2p5qbiUzDFAxbXTkjiDuGPksMBbY5TNyEsGfK4a4WGKjBCh1zeNryeuKtPotp8W1ESnwP71y"121 }`122 sampleKeyContentJwkValid = `{123 "@context": ["https://w3id.org/wallet/v1"],124 "id": "did:example:123456789abcdefghi#z6MkiEh8RQL83nkPo8ehDeX7",125 "controller": "did:example:123456789abcdefghi",126 "type": "Ed25519VerificationKey2018",127 "privateKeyJwk": {128 "kty": "OKP",129 "d":"Dq5t2WS3OMzcpkh8AyVxJs5r9v4L39ocIz9CpUOqM40",130 "crv": "Ed25519",131 "x": "ODaPFurJgFcoVCUYEmgOJpWOtPlOYbHSugasscKWqDM",132 "kid":"z6MkiEh8RQL83nkPo8ehDeX7"133 }134 }`135)136func TestContentTypes(t *testing.T) {137 t.Run("test content types", func(t *testing.T) {138 tests := []struct {139 name string140 inputs []string141 expected []ContentType142 fail bool143 }{144 {145 name: "validation success",146 inputs: []string{"collection", "credential", "didResolutionResponse", "metadata", "connection", "key"},147 expected: []ContentType{Collection, Credential, DIDResolutionResponse, Metadata, Connection, Key},148 },149 {150 name: "validation error",151 inputs: []string{"collECtion", "CRED", "VC", "DID", ""},152 fail: true,153 },154 }155 t.Parallel()156 for _, test := range tests {157 tc := test158 t.Run(tc.name, func(t *testing.T) {159 for i, input := range tc.inputs {160 ct := ContentType(input)161 if tc.fail {162 require.Error(t, ct.IsValid())163 return164 }165 require.NoError(t, ct.IsValid())166 require.Equal(t, tc.expected[i], ct)167 require.Equal(t, ct.Name(), input)168 }169 })170 }171 })172}173func TestContentStores(t *testing.T) {174 token := uuid.New().String()175 require.NoError(t, keyManager().saveKeyManger(uuid.New().String(), token,176 &mockkms.KeyManager{}, 1000*time.Millisecond))177 t.Run("create new content store - success", func(t *testing.T) {178 sp := getMockStorageProvider()179 // create new store180 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})181 require.NotEmpty(t, contentStore)182 require.Empty(t, sp.config.TagNames)183 // open store184 require.NoError(t, contentStore.Open(token, &unlockOpts{}))185 require.EqualValues(t, sp.config.TagNames,186 []string{"collection", "credential", "connection", "didResolutionResponse", "connection", "key"})187 // close store188 require.True(t, contentStore.Close())189 store, err := contentStore.open(token)190 require.Empty(t, store)191 require.True(t, errors.Is(err, ErrWalletLocked))192 })193 t.Run("create new content store for EDV profile - success", func(t *testing.T) {194 sp := getMockStorageProvider()195 masterLock, err := getDefaultSecretLock(samplePassPhrase)196 require.NoError(t, err)197 masterLockCipherText, err := createMasterLock(masterLock)198 require.NoError(t, err)199 require.NotEmpty(t, masterLockCipherText)200 profileInfo := &profile{201 ID: uuid.New().String(),202 User: uuid.New().String(),203 MasterLockCipher: masterLockCipherText,204 EDVConf: &edvConf{205 ServerURL: sampleEDVServerURL,206 VaultID: sampleEDVVaultID,207 },208 }209 tkn, err := keyManager().createKeyManager(profileInfo, sp, &unlockOpts{passphrase: samplePassPhrase})210 require.NoError(t, err)211 require.NotEmpty(t, tkn)212 kmgr, err := keyManager().getKeyManger(tkn)213 require.NoError(t, err)214 require.NotEmpty(t, kmgr)215 err = profileInfo.setupEDVEncryptionKey(kmgr)216 require.NoError(t, err)217 err = profileInfo.setupEDVMacKey(kmgr)218 require.NoError(t, err)219 // create new store220 contentStore := newContentStore(sp, profileInfo)221 require.NotEmpty(t, contentStore)222 require.Empty(t, sp.config.TagNames)223 // open store224 require.NoError(t, contentStore.Open(tkn, &unlockOpts{225 edvOpts: []edv.RESTProviderOption{226 edv.WithFullDocumentsReturnedFromQueries(),227 edv.WithBatchEndpointExtension(),228 },229 }))230 // close store231 require.True(t, contentStore.Close())232 store, err := contentStore.open(tkn)233 require.Empty(t, store)234 require.True(t, errors.Is(err, ErrWalletLocked))235 })236 t.Run("open store - failure", func(t *testing.T) {237 sp := getMockStorageProvider()238 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})239 // open store error240 sp.ErrOpenStoreHandle = errors.New(sampleContenttErr)241 err := contentStore.Open(token, &unlockOpts{})242 require.Error(t, err)243 require.Contains(t, err.Error(), sampleContenttErr)244 require.Contains(t, err.Error(), "failed to open store")245 // set store config error246 sp.ErrOpenStoreHandle = nil247 sp.failure = errors.New(sampleContenttErr)248 err = contentStore.Open(token, &unlockOpts{})249 require.Error(t, err)250 require.Contains(t, err.Error(), sampleContenttErr)251 require.Contains(t, err.Error(), "failed to set store config")252 sp.ErrOpenStoreHandle = nil253 sp.failure = nil254 sp.Store.ErrClose = errors.New(sampleContenttErr)255 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})256 require.NoError(t, contentStore.Open(token, &unlockOpts{}))257 require.True(t, contentStore.Close())258 })259 t.Run("save to store - success", func(t *testing.T) {260 sp := getMockStorageProvider()261 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})262 require.NotEmpty(t, contentStore)263 require.NoError(t, contentStore.Open(token, &unlockOpts{}))264 err := contentStore.Save(token, Collection, []byte(sampleContentValid))265 require.NoError(t, err)266 // store is open but invalid auth token267 err = contentStore.Save(sampleFakeTkn, Collection, []byte(sampleContentValid))268 require.True(t, errors.Is(err, ErrInvalidAuthToken))269 err = contentStore.Save(sampleFakeTkn,270 Credential, []byte(sampleUDCVC), AddByCollection("test"))271 require.True(t, errors.Is(err, ErrInvalidAuthToken))272 })273 t.Run("save content to store without ID - success", func(t *testing.T) {274 sp := getMockStorageProvider()275 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})276 require.NotEmpty(t, contentStore)277 require.NoError(t, contentStore.Open(token, &unlockOpts{}))278 err := contentStore.Save(token, Collection, []byte(sampleContentNoID))279 require.NoError(t, err)280 })281 t.Run("save to doc resolution to store - success", func(t *testing.T) {282 sp := getMockStorageProvider()283 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})284 require.NotEmpty(t, contentStore)285 require.NoError(t, contentStore.Open(token, &unlockOpts{}))286 err := contentStore.Save(token, DIDResolutionResponse, []byte(didResolutionResult))287 require.NoError(t, err)288 // get by DID ID289 response, err := contentStore.Get(token,290 "did:key:z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg", DIDResolutionResponse)291 require.NoError(t, err)292 require.NotEmpty(t, response)293 require.Equal(t, string(response), didResolutionResult)294 // store is open but invalid auth token295 response, err = contentStore.Get(sampleFakeTkn,296 "did:key:z6Mks8mvCnVx4HQcoq7ZwvpTbMnoRGudHSiEpXhMf6VW8XMg", DIDResolutionResponse)297 require.True(t, errors.Is(err, ErrInvalidAuthToken))298 require.Empty(t, response)299 })300 t.Run("save key to store - success", func(t *testing.T) {301 sp := getMockStorageProvider()302 sampleUser := uuid.New().String()303 contentStore := newContentStore(sp, &profile{ID: sampleUser})304 require.NotEmpty(t, contentStore)305 // wallet locked306 err := contentStore.Save(sampleFakeTkn, Key, []byte(sampleKeyContentBase58Valid))307 require.True(t, errors.Is(err, ErrWalletLocked))308 err = contentStore.Save(sampleFakeTkn, Key, []byte(sampleKeyContentJwkValid))309 require.True(t, errors.Is(err, ErrWalletLocked))310 // unlock keymanager311 masterLock, err := getDefaultSecretLock(samplePassPhrase)312 require.NoError(t, err)313 masterLockCipherText, err := createMasterLock(masterLock)314 require.NoError(t, err)315 require.NotEmpty(t, masterLockCipherText)316 profileInfo := &profile{317 User: sampleUser,318 MasterLockCipher: masterLockCipherText,319 }320 tkn, err := keyManager().createKeyManager(profileInfo, mockstorage.NewMockStoreProvider(),321 &unlockOpts{passphrase: samplePassPhrase})322 require.NoError(t, err)323 require.NotEmpty(t, tkn)324 // import base58 private key325 err = contentStore.Save(tkn, Key, []byte(sampleKeyContentBase58Valid))326 require.NoError(t, err)327 // import jwk private key328 err = contentStore.Save(tkn, Key, []byte(sampleKeyContentJwkValid))329 require.NoError(t, err)330 // import using invalid auth token331 err = contentStore.Save(tkn+"invalid", Key, []byte(sampleKeyContentBase58Valid))332 require.True(t, errors.Is(err, ErrWalletLocked))333 })334 t.Run("save key to store - failure", func(t *testing.T) {335 sp := getMockStorageProvider()336 sampleUser := uuid.New().String()337 contentStore := newContentStore(sp, &profile{ID: sampleUser})338 require.NotEmpty(t, contentStore)339 // wallet locked340 err := contentStore.Save(token, Key, []byte(""))341 require.Error(t, err)342 require.Contains(t, err.Error(), "failed to read key contents")343 })344 t.Run("save to doc resolution to store - failure", func(t *testing.T) {345 sp := getMockStorageProvider()346 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})347 require.NotEmpty(t, contentStore)348 err := contentStore.Save(token, DIDResolutionResponse, []byte(sampleContentInvalid))349 require.Error(t, err)350 require.Contains(t, err.Error(), "invalid DID resolution response model")351 })352 t.Run("save to store - failures", func(t *testing.T) {353 sp := getMockStorageProvider()354 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})355 require.NotEmpty(t, contentStore)356 // invalid content type357 err := contentStore.Save(token, ContentType("invalid"), []byte(sampleContentValid))358 require.Error(t, err)359 require.Contains(t, err.Error(), "invalid content type 'invalid'")360 // invalid content361 err = contentStore.Save(token, Credential, []byte("--"))362 require.Error(t, err)363 require.Contains(t, err.Error(), "failed to read content to be saved")364 // store errors365 sp.Store.ErrPut = errors.New(sampleContenttErr)366 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})367 require.NotEmpty(t, contentStore)368 // wallet locked369 err = contentStore.Save(token, Credential, []byte(sampleContentValid))370 require.True(t, errors.Is(err, ErrWalletLocked))371 require.NoError(t, contentStore.Open(token, &unlockOpts{}))372 err = contentStore.Save(token, Credential, []byte(sampleContentValid))373 require.Error(t, err)374 require.Contains(t, err.Error(), sampleContenttErr)375 sp.Store.ErrGet = errors.New(sampleContenttErr)376 err = contentStore.Save(token, Credential, []byte(sampleContentValid))377 require.Error(t, err)378 require.Contains(t, err.Error(), sampleContenttErr)379 })380 t.Run("save to invalid content type - validation", func(t *testing.T) {381 sp := getMockStorageProvider()382 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})383 require.NotEmpty(t, contentStore)384 err := contentStore.Save(token, "Test", []byte("{}"))385 require.Error(t, err)386 require.Contains(t, err.Error(), "invalid content type")387 })388 t.Run("save duplicate items - validation", func(t *testing.T) {389 sp := getMockStorageProvider()390 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})391 require.NotEmpty(t, contentStore)392 require.NoError(t, contentStore.Open(token, &unlockOpts{}))393 err := contentStore.Save(token, Collection, []byte(sampleContentValid))394 require.NoError(t, err)395 // save again396 err = contentStore.Save(token, Collection, []byte(sampleContentValid))397 require.Error(t, err)398 require.Contains(t, err.Error(), "content with same type and id already exists in this wallet")399 })400 t.Run("get from store - success", func(t *testing.T) {401 sp := getMockStorageProvider()402 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})403 require.NotEmpty(t, contentStore)404 require.NoError(t, contentStore.Open(token, &unlockOpts{}))405 // save406 err := contentStore.Save(token, Collection, []byte(sampleContentValid))407 require.NoError(t, err)408 // get409 content, err := contentStore.Get(token, "did:example:123456789abcdefghi", Collection)410 require.NoError(t, err)411 require.Equal(t, sampleContentValid, string(content))412 })413 t.Run("get from store - failure", func(t *testing.T) {414 sp := getMockStorageProvider()415 sp.Store.ErrGet = errors.New(sampleContenttErr)416 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})417 require.NotEmpty(t, contentStore)418 content, err := contentStore.Get(token, "did:example:123456789abcdefghi", Collection)419 require.Empty(t, content)420 require.True(t, errors.Is(err, ErrWalletLocked))421 require.NoError(t, contentStore.Open(token, &unlockOpts{}))422 // get423 content, err = contentStore.Get(token, "did:example:123456789abcdefghi", Collection)424 require.Empty(t, content)425 require.Error(t, err)426 require.Contains(t, err.Error(), sampleContenttErr)427 })428 t.Run("remove from store - success", func(t *testing.T) {429 sp := getMockStorageProvider()430 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})431 require.NotEmpty(t, contentStore)432 require.NoError(t, contentStore.Open(token, &unlockOpts{}))433 // save434 err := contentStore.Save(token, Collection, []byte(sampleContentValid))435 require.NoError(t, err)436 // get437 content, err := contentStore.Get(token, "did:example:123456789abcdefghi", Collection)438 require.NoError(t, err)439 require.Equal(t, sampleContentValid, string(content))440 // remove441 err = contentStore.Remove(token, "did:example:123456789abcdefghi", Collection)442 require.NoError(t, err)443 // get444 content, err = contentStore.Get(token, "did:example:123456789abcdefghi", Collection)445 require.Empty(t, content)446 require.Error(t, err)447 require.True(t, errors.Is(err, storage.ErrDataNotFound))448 })449 t.Run("remove from store - failure", func(t *testing.T) {450 sp := getMockStorageProvider()451 sp.Store.ErrDelete = errors.New(sampleContenttErr)452 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})453 require.NotEmpty(t, contentStore)454 require.NoError(t, contentStore.Open(token, &unlockOpts{}))455 // save456 err := contentStore.Save(token, Collection, []byte(sampleContentValid))457 require.NoError(t, err)458 // remove459 err = contentStore.Remove(token, "did:example:123456789abcdefghi", Collection)460 require.Error(t, err)461 require.Contains(t, err.Error(), sampleContenttErr)462 require.True(t, contentStore.Close())463 err = contentStore.Remove(token, "did:example:123456789abcdefghi", Collection)464 require.True(t, errors.Is(err, ErrWalletLocked))465 })466}467func TestContentStore_GetAll(t *testing.T) {468 const vcContent = `{469 "@context": [470 "https://www.w3.org/2018/credentials/v1",471 "https://www.w3.org/2018/credentials/examples/v1"472 ],473 "credentialSchema": [],474 "credentialSubject": {475 "id": "did:example:ebfeb1f712ebc6f1c276e12ec21",476 "name": "Jayden Doe"477 },478 "id": "%s",479 "issuanceDate": "2010-01-01T19:23:24Z",480 "issuer": {481 "id": "did:example:76e12ec712ebc6f1c221ebfeb1f",482 "name": "Example University"483 },484 "type": [485 "VerifiableCredential",486 "UniversityDegreeCredential"487 ]488 }`489 const testMetadata = `{490 "@context": ["https://w3id.org/wallet/v1"],491 "id": "%s",492 "type": "Person",493 "name": "John Smith",494 "image": "https://via.placeholder.com/150",495 "description" : "Professional software developer for Acme Corp."496 }`497 token := uuid.New().String()498 require.NoError(t, keyManager().saveKeyManger(uuid.New().String(), token, &mockkms.KeyManager{}, 500*time.Millisecond))499 t.Run("get all content from store for credential type - success", func(t *testing.T) {500 sp := getMockStorageProvider()501 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})502 require.NotEmpty(t, contentStore)503 require.NoError(t, contentStore.Open(token, &unlockOpts{}))504 // save test data505 const count = 5506 for i := 0; i < count; i++ {507 require.NoError(t, contentStore.Save(token,508 Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String()))))509 require.NoError(t, contentStore.Save(token,510 Metadata, []byte(fmt.Sprintf(testMetadata, uuid.New().String()))))511 }512 allVcs, err := contentStore.GetAll(token, Credential)513 require.NoError(t, err)514 require.Len(t, allVcs, count)515 allMetadata, err := contentStore.GetAll(token, Metadata)516 require.NoError(t, err)517 require.Len(t, allMetadata, count)518 allDIDs, err := contentStore.GetAll(token, DIDResolutionResponse)519 require.NoError(t, err)520 require.Empty(t, allDIDs)521 // store is open but invalid auth token522 allMetadata, err = contentStore.GetAll(sampleFakeTkn, DIDResolutionResponse)523 require.True(t, errors.Is(err, ErrInvalidAuthToken))524 require.Empty(t, allMetadata)525 })526 t.Run("get all content from store for credential type - errors", func(t *testing.T) {527 sp := getMockStorageProvider()528 // wallet locked529 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})530 allVcs, err := contentStore.GetAll(token, Credential)531 require.True(t, errors.Is(err, ErrWalletLocked))532 require.Empty(t, allVcs)533 require.NoError(t, contentStore.Open(token, &unlockOpts{}))534 require.NoError(t, contentStore.Save(token, Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String()))))535 // iterator value error536 sp.MockStoreProvider.Store.ErrValue = errors.New(sampleContenttErr + uuid.New().String())537 allVcs, err = contentStore.GetAll(token, Credential)538 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrValue))539 require.Empty(t, allVcs)540 // iterator value error541 sp.MockStoreProvider.Store.ErrKey = errors.New(sampleContenttErr + uuid.New().String())542 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})543 require.NotEmpty(t, contentStore)544 require.NoError(t, contentStore.Open(token, &unlockOpts{}))545 allVcs, err = contentStore.GetAll(token, Credential)546 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrKey))547 require.Empty(t, allVcs)548 // iterator next error549 sp.MockStoreProvider.Store.ErrNext = errors.New(sampleContenttErr + uuid.New().String())550 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})551 require.NotEmpty(t, contentStore)552 require.NoError(t, contentStore.Open(token, &unlockOpts{}))553 require.NoError(t, contentStore.Save(token, Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String()))))554 allVcs, err = contentStore.GetAll(token, Credential)555 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrNext))556 require.Empty(t, allVcs)557 // iterator next error558 sp.MockStoreProvider.Store.ErrQuery = errors.New(sampleContenttErr + uuid.New().String())559 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})560 require.NotEmpty(t, contentStore)561 require.NoError(t, contentStore.Open(token, &unlockOpts{}))562 allVcs, err = contentStore.GetAll(token, Credential)563 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrQuery))564 require.Empty(t, allVcs)565 })566}567func TestContentDIDResolver(t *testing.T) {568 token := uuid.New().String()569 require.NoError(t, keyManager().saveKeyManger(uuid.New().String(), token, &mockkms.KeyManager{}, 500*time.Millisecond))570 t.Run("create new content store - success", func(t *testing.T) {571 sp := getMockStorageProvider()572 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})573 require.NotEmpty(t, contentStore)574 require.NoError(t, contentStore.Open(token, &unlockOpts{}))575 // save custom DID576 err := contentStore.Save(token, DIDResolutionResponse, []byte(sampleDocResolutionResponse))577 require.NoError(t, err)578 contentVDR := newContentBasedVDR(token, &vdr.MockVDRegistry{}, contentStore)579 require.NotEmpty(t, contentVDR)580 didDoc, err := contentVDR.Resolve("did:key:z6MknC1wwS6DEYwtGbZZo2QvjQjkh2qSBjb4GYmbye8dv4S5")581 require.NoError(t, err)582 require.NotEmpty(t, didDoc)583 require.Equal(t, "did:key:z6MknC1wwS6DEYwtGbZZo2QvjQjkh2qSBjb4GYmbye8dv4S5", didDoc.DIDDocument.ID)584 require.NotEmpty(t, didDoc.DIDDocument.Authentication)585 didDoc, err = contentVDR.Resolve("did:key:invalid")586 require.Error(t, err)587 require.Equal(t, vdrapi.ErrNotFound, err)588 require.Empty(t, didDoc)589 })590 t.Run("create new content store - errors", func(t *testing.T) {591 sp := getMockStorageProvider()592 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})593 require.NotEmpty(t, contentStore)594 contentVDR := newContentBasedVDR(token, &vdr.MockVDRegistry{}, contentStore)595 require.NotEmpty(t, contentVDR)596 // wallet locked597 didDoc, err := contentVDR.Resolve("did:key:invalid")598 require.True(t, errors.Is(err, ErrWalletLocked))599 require.Empty(t, didDoc)600 // open store601 require.NoError(t, contentStore.Open(token, &unlockOpts{}))602 // DID not found603 didDoc, err = contentVDR.Resolve("did:key:invalid")604 require.Error(t, err)605 require.Equal(t, vdrapi.ErrNotFound, err)606 require.Empty(t, didDoc)607 // parse error608 st, err := contentStore.open(token)609 require.NoError(t, err)610 err = st.Put(getContentKeyPrefix(DIDResolutionResponse,611 "did:key:z6MknC1wwS6DEYwtGbZZo2QvjQjkh2qSBjb4GYmbye8dv4S5"), []byte(sampleInvalidDIDContent))612 require.NoError(t, err)613 didDoc, err = contentVDR.Resolve("did:key:z6MknC1wwS6DEYwtGbZZo2QvjQjkh2qSBjb4GYmbye8dv4S5")614 require.Error(t, err)615 require.Contains(t, err.Error(), "failed to parse stored DID")616 require.Empty(t, didDoc)617 })618}619func TestContentStore_Collections(t *testing.T) {620 const vcContent = `{621 "@context": [622 "https://www.w3.org/2018/credentials/v1",623 "https://www.w3.org/2018/credentials/examples/v1"624 ],625 "credentialSchema": [],626 "credentialSubject": {627 "id": "did:example:ebfeb1f712ebc6f1c276e12ec21",628 "name": "Jayden Doe"629 },630 "id": "%s",631 "issuanceDate": "2010-01-01T19:23:24Z",632 "issuer": {633 "id": "did:example:76e12ec712ebc6f1c221ebfeb1f",634 "name": "Example University"635 },636 "type": [637 "VerifiableCredential",638 "UniversityDegreeCredential"639 ]640 }`641 const testMetadata = `{642 "@context": ["https://w3id.org/wallet/v1"],643 "id": "%s",644 "type": "Person",645 "name": "John Smith",646 "image": "https://via.placeholder.com/150",647 "description" : "Professional software developer for Acme Corp."648 }`649 const connection = `{650 "@context": ["https://w3id.org/wallet/v1"],651 "id": "%s",652 "name": "My Health Record Certifier",653 "image": "https://via.placeholder.com/150",654 "description" : "The identifier that issues health record credentials.",655 "tags": ["professional"],656 "correlation": ["4058a72a-9523-11ea-bb37-0242ac130002"],657 "type": "Connection"658 }`659 const orgCollection = `{660 "@context": ["https://w3id.org/wallet/v1"],661 "id": "did:example:acme123456789abcdefghi",662 "type": "Organization",663 "name": "Acme Corp.",664 "image": "https://via.placeholder.com/150",665 "description" : "A software company.",666 "tags": ["professional", "organization"],667 "correlation": ["4058a72a-9523-11ea-bb37-0242ac130002"]668 }`669 const collectionID = "did:example:acme123456789abcdefghi"670 token := uuid.New().String()671 require.NoError(t, keyManager().saveKeyManger(uuid.New().String(), token, &mockkms.KeyManager{}, 500*time.Millisecond))672 t.Run("contents by collection - success", func(t *testing.T) {673 sp := getMockStorageProvider()674 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})675 require.NotEmpty(t, contentStore)676 require.NoError(t, contentStore.Open(token, &unlockOpts{}))677 // save a collection678 require.NoError(t, contentStore.Save(token, Collection, []byte(orgCollection)))679 const addedWithoutCollection = 4680 const addedToCollection = 3681 // save test data682 for i := 0; i < addedToCollection; i++ {683 require.NoError(t, contentStore.Save(token,684 Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String())), AddByCollection(collectionID)))685 require.NoError(t, contentStore.Save(token,686 Metadata, []byte(fmt.Sprintf(testMetadata, uuid.New().String())), AddByCollection(collectionID)))687 }688 require.NoError(t, contentStore.Save(token,689 DIDResolutionResponse, []byte(didResolutionResult), AddByCollection(collectionID)))690 for i := 0; i < addedWithoutCollection; i++ {691 require.NoError(t, contentStore.Save(token,692 Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String()))))693 require.NoError(t, contentStore.Save(token,694 Metadata, []byte(fmt.Sprintf(testMetadata, uuid.New().String()))))695 require.NoError(t, contentStore.Save(token,696 Connection, []byte(fmt.Sprintf(connection, uuid.New().String()))))697 }698 allVcs, err := contentStore.GetAll(token, Credential)699 require.NoError(t, err)700 require.Len(t, allVcs, addedWithoutCollection+addedToCollection)701 allVcs, err = contentStore.GetAllByCollection(token, collectionID, Credential)702 require.NoError(t, err)703 require.Len(t, allVcs, addedToCollection)704 allMetadata, err := contentStore.GetAll(token, Metadata)705 require.NoError(t, err)706 require.Len(t, allMetadata, addedWithoutCollection+addedToCollection)707 allMetadata, err = contentStore.GetAllByCollection(token, collectionID, Metadata)708 require.NoError(t, err)709 require.Len(t, allMetadata, addedToCollection)710 allDIDs, err := contentStore.GetAll(token, DIDResolutionResponse)711 require.NoError(t, err)712 require.Len(t, allDIDs, 1)713 allDIDs, err = contentStore.GetAllByCollection(token, collectionID, DIDResolutionResponse)714 require.NoError(t, err)715 require.Len(t, allDIDs, 1)716 allConns, err := contentStore.GetAll(token, Connection)717 require.NoError(t, err)718 require.Len(t, allConns, addedWithoutCollection)719 allConns, err = contentStore.GetAllByCollection(token, collectionID, Connection)720 require.NoError(t, err)721 require.Empty(t, allConns)722 })723 t.Run("contents by collection - failure", func(t *testing.T) {724 sp := getMockStorageProvider()725 contentStore := newContentStore(sp, &profile{ID: uuid.New().String()})726 require.NotEmpty(t, contentStore)727 require.NoError(t, contentStore.Open(token, &unlockOpts{}))728 err := contentStore.Save(token,729 DIDResolutionResponse, []byte(didResolutionResult), AddByCollection(collectionID+"invalid"))730 require.Error(t, err)731 require.Contains(t, err.Error(), "failed to find existing collection")732 err = contentStore.Save(token,733 Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String())), AddByCollection(collectionID+"invalid"))734 require.Error(t, err)735 require.Contains(t, err.Error(), "failed to find existing collection")736 // save a collection737 require.NoError(t, contentStore.Save(token, Collection, []byte(orgCollection)))738 require.NoError(t, contentStore.Save(token, Credential, []byte(fmt.Sprintf(vcContent, uuid.New().String())),739 AddByCollection(collectionID)))740 // get content error741 sp.MockStoreProvider.Store.ErrGet = errors.New(sampleContenttErr + uuid.New().String())742 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})743 require.NotEmpty(t, contentStore)744 require.NoError(t, contentStore.Open(token, &unlockOpts{}))745 allVcs, err := contentStore.GetAllByCollection(token, collectionID, Credential)746 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrGet))747 require.Empty(t, allVcs)748 // iterator value error749 sp.MockStoreProvider.Store.ErrValue = errors.New(sampleContenttErr + uuid.New().String())750 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})751 require.NotEmpty(t, contentStore)752 require.NoError(t, contentStore.Open(token, &unlockOpts{}))753 allVcs, err = contentStore.GetAllByCollection(token, collectionID, Credential)754 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrValue))755 require.Empty(t, allVcs)756 // iterator value error757 sp.MockStoreProvider.Store.ErrKey = errors.New(sampleContenttErr + uuid.New().String())758 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})759 require.NotEmpty(t, contentStore)760 require.NoError(t, contentStore.Open(token, &unlockOpts{}))761 allVcs, err = contentStore.GetAllByCollection(token, collectionID, Credential)762 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrKey))763 require.Empty(t, allVcs)764 // iterator next error765 sp.MockStoreProvider.Store.ErrNext = errors.New(sampleContenttErr + uuid.New().String())766 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})767 require.NotEmpty(t, contentStore)768 require.NoError(t, contentStore.Open(token, &unlockOpts{}))769 allVcs, err = contentStore.GetAllByCollection(token, collectionID, Credential)770 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrNext))771 require.Empty(t, allVcs)772 // iterator next error773 sp.MockStoreProvider.Store.ErrQuery = errors.New(sampleContenttErr + uuid.New().String())774 contentStore = newContentStore(sp, &profile{ID: uuid.New().String()})775 require.NotEmpty(t, contentStore)776 require.NoError(t, contentStore.Open(token, &unlockOpts{}))777 allVcs, err = contentStore.GetAllByCollection(token, collectionID, Credential)778 require.True(t, errors.Is(err, sp.MockStoreProvider.Store.ErrQuery))779 require.Empty(t, allVcs)780 // wallet locked error781 require.True(t, contentStore.Close())782 allVcs, err = contentStore.GetAllByCollection(token, collectionID, Credential)783 require.True(t, errors.Is(err, ErrWalletLocked))784 require.Empty(t, allVcs)785 })786}787type mockStorageProvider struct {788 *mockstorage.MockStoreProvider789 config storage.StoreConfiguration790 failure error791}792func (s *mockStorageProvider) SetStoreConfig(name string, config storage.StoreConfiguration) error {793 s.config = config794 return s.failure795}796func (s *mockStorageProvider) GetStoreConfig(name string) (storage.StoreConfiguration, error) {797 return s.config, nil798}799func getMockStorageProvider() *mockStorageProvider {800 return &mockStorageProvider{MockStoreProvider: mockstorage.NewMockStoreProvider()}801}...

Full Screen

Full Screen

metadata_test.go

Source:metadata_test.go Github

copy

Full Screen

...5 "github.com/jfrog/jfrog-client-go/artifactory/services/utils"6 . "github.com/poy/onpar/expect"7 . "github.com/poy/onpar/matchers"8)9func TestMetadata(t *testing.T) {10 tests := []struct {11 description string12 input artifactory.Artifact13 expected string14 }{15 {16 description: "empty artifact",17 input: artifactory.Artifact{File: utils.FileInfo{}, Item: utils.ResultItem{}},18 expected: `[{"name":"artifactory-path","value":""},{"name":"local-path","value":""},{"name":"created","value":""},{"name":"modified","value":""},{"name":"name","value":""},{"name":"repo","value":""},{"name":"size","value":"0"},{"name":"type","value":""},{"name":"properties","value":"null"}]`,19 },20 {21 description: "filled properties",22 input: artifactory.Artifact{23 File: utils.FileInfo{},...

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 repo, err := vcs.RepoRootForImportPath("golang.org/x/tools", false)4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(repo.Root)8 fmt.Println(repo.VCS.Cmd)9 fmt.Println(repo.VCS.CreateCmd)10 fmt.Println(repo.VCS.DownloadCmd)11 fmt.Println(repo.VCS.SyncCmd)12 fmt.Println(repo.VCS.TagSyncCmd)13 fmt.Println(repo.VCS.BrowseCmd)14 fmt.Println(repo.VCS.UpdateCmd)15 fmt.Println(repo.VCS.RootPattern)16 fmt.Println(repo.VCS.RemoteRepo)17 fmt.Println(repo.VCS.RemoteRepoForNew)18 fmt.Println(repo.VCS.RemoteRepoForUpload)19 fmt.Println(repo.VCS.RemoteRepoForDownload)20 fmt.Println(repo.VCS.RemoteRepoForBrowse)21 fmt.Println(repo.VCS.RemoteRepoForTagSync)22 fmt.Println(repo.VCS.RemoteRepoForUpdate)23 fmt.Println(repo.VCS.RemoteRepoForTag)24 fmt.Println(repo.VCS.RemoteRepoForTagList)25 fmt.Println(repo.VCS.RemoteRepoForTagDelete)26 fmt.Println(repo.VCS.RemoteRepoForBranch)27 fmt.Println(repo.VCS.RemoteRepoForBranchList)28 fmt.Println(repo.VCS.RemoteRepoForBranchDelete)29 fmt.Println(repo.VCS.RemoteRepoForBranchRename)30 fmt.Println(repo.VCS.RemoteRepoForBranchSetDefault)31 fmt.Println(repo.VCS.RemoteRepoForBranchSync)32 fmt.Println(repo.VCS.RemoteRepoForBranchSyncToDefault)33 fmt.Println(repo.VCS.RemoteRepoForBranchSyncFromDefault)34 fmt.Println(repo.VCS.RemoteRepoForBranchSyncFrom)35 fmt.Println(repo.VCS.RemoteRepoForChange)36 fmt.Println(repo.VCS.RemoteRepoForChangeList)37 fmt.Println(repo.VCS.RemoteRepoForChangeListOpen)38 fmt.Println(repo.VCS.RemoteRepoForChangeListClose)39 fmt.Println(repo.VCS.RemoteRepoForChangeListDelete)40 fmt.Println(repo.VCS.RemoteRepoForChangeListRevert)41 fmt.Println(repo.VCS.RemoteRepoForChangeListDescription)42 fmt.Println(repo.VCS.RemoteRepoForChangeListDescriptionSet)43 fmt.Println(repo.VCS.RemoteRepoForChangeListFiles)44 fmt.Println(repo.VCS.RemoteRepoForChange

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("hello")4 vcs.Register("git", git.New(git.GitCmd))5 vcs.Register("hg", hg.New(hg.HgCmd))6 vcs, err := vcs.New("git")7 if err != nil {8 fmt.Println("Error is :", err)9 }10 metadata, err := vcs.Metadata("C:/Users/Prashant/GoWorkspace/src/github.com/robfig/revel")11 if err != nil {12 fmt.Println("Error is :", err)13 }14 fmt.Println("metadata is :", metadata)15}16metadata is : {1.0.0 2016-07-11 16:03:50 +0530 IST}

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 sess := session.New()4 service := services.GetVirtualGuestService(sess)5 result, err := service.Id(virtualGuestId).Metadata()6 if err != nil {7 fmt.Println("Error: ", err)8 }9 fmt.Println("Metadata: ", result)10}11import (12func main() {13 sess := session.New()14 service := services.GetVirtualGuestService(sess)15 metadata := []datatypes.Virtual_Guest_Metadata{datatypes.Virtual_Guest_Metadata{Key: "key1", Value: "value1"}, datatypes.Virtual_Guest_Metadata{Key: "key2", Value: "value2"}}16 result, err := service.Id(virtualGuestId).SetMetadata(metadata)17 if err != nil {18 fmt.Println("Error: ", err)19 }20 fmt.Println("Metadata: ", result)21}22import (23func main() {24 sess := session.New()25 service := services.GetVirtualGuestService(sess)

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(vcs.TestMetadata(golenv.GetEnv("HOME") + "/.gol"))4}5import (6func main() {7 fmt.Println(vcs.TestMetadata(golenv.GetEnv("HOME") + "/.gol"))8}9import (10func main() {11 fmt.Println(vcs.TestMetadata(golenv.GetEnv("HOME") + "/.gol"))12}13import (14func main() {15 fmt.Println(vcs.TestMetadata(golenv.GetEnv("HOME") + "/.gol"))16}17import (18func main() {19 fmt.Println(vcs.TestMetadata(golenv.GetEnv("HOME") + "/.gol"))20}21import (

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 x = vcs.New()4 fmt.Println(x.TestMetadata())5}6import (7func main() {8 x = vcs.New()9 fmt.Println(x.TestMetadata())10}11import (12func main() {13 x = vcs.New()14 fmt.Println(x.TestMetadata())15}16import (17func main() {18 x = vcs.New()19 fmt.Println(x.TestMetadata())20}21import (22func main() {23 x = vcs.New()24 fmt.Println(x.TestMetadata())25}26import (27func main() {28 x = vcs.New()29 fmt.Println(x.TestMetadata())30}31import (32func main() {33 x = vcs.New()34 fmt.Println(x.TestMetadata())35}36import (37func main() {38 x = vcs.New()39 fmt.Println(x.TestMetadata())40}41import (42func main() {43 x = vcs.New()44 fmt.Println(x.TestMetadata())45}

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m = vcs.TestMetadata()4 fmt.Println(m)5}6{2012-10-19 10:00:00 +0000 UTC 2012-10-19 10:00:00 +0000 UTC}7type Person struct {8}9p := Person{"John", 20}10fmt.Println(p.Name)11struct_name{field1, field2, field3}12p := Person{Name: "John", Age: 20}13fmt.Println(p.Name)

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v := vcs.NewVcs()4 v.TestMetadata()5 fmt.Println(v)6}7import (8type Vcs struct {9}10func (v *Vcs) TestMetadata() {11 fmt.Println("TestMetadata called")12}13func NewVcs() *Vcs {14 return &Vcs{}15}16import (17func TestVcs(t *testing.T) {18 v := NewVcs()19 v.TestMetadata()20}21--- PASS: TestVcs (0.00s)

Full Screen

Full Screen

TestMetadata

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 vcs := vcs.New()4 meta, err := vcs.TestMetadata("2.go")5 if err != nil {6 fmt.Println("Error:", err)7 }

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful