feat(org): add organization and membership contract and storage
This commit is contained in:
1 parent
a0551a34b8
commit
bdc5855001
90 files changed
+17545
-480
No files matched your search
@@ -0,0 +1,576 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
)
|
||||
|
||||
// Organization request fixtures shared by the organization tests.
|
||||
const (
|
||||
myOrganizationsPath = "/api/v1/me/organizations"
|
||||
organizationsPath = "/api/v1/organizations"
|
||||
organizationPath = organizationsPath + "/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"
|
||||
|
||||
validOrganizationContacts = `{"website":"https://payments.example.com","email":"careers@payments.example.com","phone":"+74950000000","telegram":"@payments_careers"}`
|
||||
emptyOrganizationContacts = `{"website":null,"email":null,"phone":null,"telegram":null}`
|
||||
)
|
||||
|
||||
// organizationBody builds a JSON object from the given members.
|
||||
func organizationBody(members ...string) string {
|
||||
return "{" + strings.Join(members, ",") + "}"
|
||||
}
|
||||
|
||||
// The schemas alone must accept the profile a company may send and reject
|
||||
// what no request may carry: a role, an owner, a verification level or its
|
||||
// basis, the members, the card, a version, or an identifier. Security accepts
|
||||
// the session here, so the request reaches validation; a valid request then
|
||||
// answers 501 until the operations are implemented. The rules that need
|
||||
// storage, such as the website host or the version, pass the schema and are
|
||||
// checked by the server.
|
||||
func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
|
||||
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
|
||||
create := func(body string) identityRequest {
|
||||
return identityRequest{method: http.MethodPost, path: organizationsPath, body: body, headers: command}
|
||||
}
|
||||
update := func(members ...string) identityRequest {
|
||||
return identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(append([]string{`"expected_version":1`}, members...)...), headers: session}
|
||||
}
|
||||
forbiddenFields := []string{
|
||||
`"role":"owner"`,
|
||||
`"owner_id":"01928f7a-0000-7000-8000-00000000c0de"`,
|
||||
`"verification_level":"e1"`,
|
||||
`"verification":{"level":"e2","basis":"manual_review","changed_at":"2026-10-06T09:00:00Z"}`,
|
||||
`"verification_basis":"corporate_domain"`,
|
||||
`"members":[{"user_id":"01928f7a-0000-7000-8000-00000000c0de","role":"owner"}]`,
|
||||
`"membership":{"organization_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","role":"owner","state":"active","joined_at":"2026-10-06T09:00:00Z"}`,
|
||||
`"candidate_card":{}`,
|
||||
`"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`,
|
||||
`"version":3`,
|
||||
`"created_at":"2026-10-06T09:00:00Z"`,
|
||||
}
|
||||
|
||||
type expectation struct {
|
||||
name string
|
||||
request identityRequest
|
||||
location api.ProblemFieldLocation
|
||||
pointer string
|
||||
code string
|
||||
}
|
||||
tests := make([]expectation, 0, 36+2*len(forbiddenFields))
|
||||
tests = append(tests, []expectation{
|
||||
{
|
||||
name: "list",
|
||||
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=20", headers: session},
|
||||
},
|
||||
{
|
||||
name: "list with a limit above the maximum",
|
||||
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=101", headers: session},
|
||||
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "list with a malformed cursor",
|
||||
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?cursor=not%20a%20cursor", headers: session},
|
||||
location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name only",
|
||||
request: create(organizationBody(`"name":"ООО Пример Платежи"`)),
|
||||
},
|
||||
{
|
||||
name: "create with a complete card",
|
||||
request: create(organizationBody(
|
||||
`"name":"ООО Пример Платежи"`,
|
||||
`"description":"Платежный сервис.\nСобственное ядро."`,
|
||||
`"sphere":"Платежи и финансовые сервисы"`,
|
||||
`"contacts":`+validOrganizationContacts,
|
||||
`"representatives":[{"name":"Анна Тестова","job_title":"Руководитель по подбору"}]`,
|
||||
)),
|
||||
},
|
||||
{
|
||||
name: "create with an explicit null description and sphere",
|
||||
request: create(organizationBody(`"name":"ООО Пример"`, `"description":null`, `"sphere":null`, `"contacts":`+emptyOrganizationContacts, `"representatives":[]`)),
|
||||
},
|
||||
{
|
||||
// A domain rule of the server: the schema accepts any https
|
||||
// string without credentials, and the host rules come after it.
|
||||
name: "create with a website that has a port",
|
||||
request: create(organizationBody(`"name":"ООО Пример"`, `"contacts":{"website":"https://payments.example.com:8443","email":null,"phone":null,"telegram":null}`)),
|
||||
},
|
||||
{
|
||||
name: "create without a name",
|
||||
request: create(organizationBody(`"sphere":"Платежи"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "required",
|
||||
},
|
||||
{
|
||||
name: "create without an Idempotency-Key",
|
||||
request: identityRequest{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: session},
|
||||
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
|
||||
},
|
||||
{
|
||||
name: "create with an empty name",
|
||||
request: create(organizationBody(`"name":""`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name over 200 characters",
|
||||
request: create(organizationBody(`"name":"` + strings.Repeat("я", 201) + `"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name that has a leading space",
|
||||
request: create(organizationBody(`"name":" ООО"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name that has a line break",
|
||||
request: create(organizationBody(`"name":"ООО\nПример"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a sphere that has a trailing space",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"sphere":"Платежи "`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/sphere", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with an empty description",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"description":""`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with contacts that omit a field",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "required",
|
||||
},
|
||||
{
|
||||
name: "create with a personal contact kind",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":null,"home_address":"ул. Тестовая"}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with an http website",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"http://payments.example.com","email":null,"phone":null,"telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a website that has credentials",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"https://user:secret@payments.example.com","email":null,"phone":null,"telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a phone that is not E.164",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":"8 495 000-00-00","telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/phone", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a Telegram username without the at sign",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":"payments_careers"}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with an email that is not an address",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":"careers","phone":null,"telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/email", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with eleven representatives",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"representatives":[`+
|
||||
strings.TrimSuffix(strings.Repeat(`{"name":"Имя","job_title":"Должность"},`, 11), ",")+`]`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
// A failure inside an array element during decoding reports the
|
||||
// pointer of the array, because jx reports no element index.
|
||||
name: "create with a representative that has no job title",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова"}]`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a representative contact",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова","job_title":"HR","email":"anna@example.com"}]`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with the version only",
|
||||
request: update(),
|
||||
},
|
||||
{
|
||||
name: "update of the profile with explicit nulls",
|
||||
request: update(`"description":null`, `"sphere":null`),
|
||||
},
|
||||
{
|
||||
name: "update of the contacts and representatives as a whole",
|
||||
request: update(`"contacts":`+emptyOrganizationContacts, `"representatives":[]`),
|
||||
},
|
||||
{
|
||||
name: "update without expected_version",
|
||||
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"name":"ООО Новое"`), headers: session},
|
||||
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
|
||||
},
|
||||
{
|
||||
name: "update with expected_version zero",
|
||||
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":0`), headers: session},
|
||||
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with a null name",
|
||||
request: update(`"name":null`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with null representatives",
|
||||
request: update(`"representatives":null`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with null contacts",
|
||||
request: update(`"contacts":null`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "read",
|
||||
request: identityRequest{method: http.MethodGet, path: organizationPath, headers: session},
|
||||
},
|
||||
{
|
||||
name: "read an organization identifier that is not a UUID",
|
||||
request: identityRequest{method: http.MethodGet, path: organizationsPath + "/acme", headers: session},
|
||||
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update an organization identifier that is not a UUID",
|
||||
request: identityRequest{method: http.MethodPatch, path: organizationsPath + "/acme", body: organizationBody(`"expected_version":1`), headers: session},
|
||||
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
|
||||
},
|
||||
}...)
|
||||
// No request of either command may carry a right or a trust level, each
|
||||
// one alone, as a whole-body rejection of an unknown field.
|
||||
for _, field := range forbiddenFields {
|
||||
tests = append(tests,
|
||||
expectation{
|
||||
name: "create with the forbidden field " + strings.SplitN(field, ":", 2)[0],
|
||||
request: create(organizationBody(`"name":"ООО Пример"`, field)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
|
||||
},
|
||||
expectation{
|
||||
name: "update with the forbidden field " + strings.SplitN(field, ":", 2)[0],
|
||||
request: update(field),
|
||||
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
response := serveIdentityRequest(t, router, test.request)
|
||||
|
||||
switch test.code {
|
||||
case "":
|
||||
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
|
||||
default:
|
||||
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
|
||||
for _, field := range body.Errors {
|
||||
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Every organization operation requires an employer session; DenyAllSecurity
|
||||
// grants none, with or without a cookie and a CSRF token, and no request can
|
||||
// name another account.
|
||||
func TestOrganizationAccessBeforeImplementation(t *testing.T) {
|
||||
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
|
||||
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
|
||||
for _, test := range []identityRequest{
|
||||
{method: http.MethodGet, path: myOrganizationsPath},
|
||||
{method: http.MethodGet, path: myOrganizationsPath, headers: map[string]string{"Cookie": testSessionCookie}},
|
||||
{method: http.MethodGet, path: myOrganizationsPath + "?user_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}},
|
||||
{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: command},
|
||||
{method: http.MethodGet, path: organizationPath},
|
||||
{method: http.MethodGet, path: organizationPath, headers: map[string]string{"Cookie": testSessionCookie}},
|
||||
{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":1`, `"name":"ООО Новое"`), headers: session},
|
||||
} {
|
||||
t.Run(test.method+" "+test.path, func(t *testing.T) {
|
||||
router := newTestRouter(t, func(context.Context) error { return nil })
|
||||
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A role and a verification level never travel in the company DTOs: not in
|
||||
// the response a member reads, not in the create or the update body. The
|
||||
// role lives in OrganizationMembership, which a client cannot send, and the
|
||||
// level in OrganizationVerification, which only the response carries.
|
||||
func TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests(t *testing.T) {
|
||||
raising := []string{
|
||||
"role", "roles", "verification", "verification_level", "verification_basis", "level", "basis", "trust_level",
|
||||
"owner", "owner_id", "members", "membership", "user_id", "account_id", "permissions", "e0", "e1", "e2", "e3",
|
||||
}
|
||||
for _, dto := range []any{api.Organization{}, api.OrganizationCreate{}, api.OrganizationUpdate{}, api.CandidateOrganizationCard{}, api.OrganizationContactChannels{}, api.OrganizationRepresentative{}} {
|
||||
typ := reflect.TypeOf(dto)
|
||||
for i := range typ.NumField() {
|
||||
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
|
||||
isVerificationReadModel := (typ == reflect.TypeFor[api.Organization]() && name == "verification") ||
|
||||
(typ == reflect.TypeFor[api.CandidateOrganizationCard]() && name == "verification_level")
|
||||
for _, field := range raising {
|
||||
if name == field && !isVerificationReadModel {
|
||||
t.Errorf("%s exposes the field %q", typ.Name(), name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The two request DTOs have no verification field at all, not even the
|
||||
// read-only ones of the response.
|
||||
for _, dto := range []any{api.OrganizationCreate{}, api.OrganizationUpdate{}} {
|
||||
assertNoJSONFields(t, dto, []string{"verification", "verification_level", "candidate_card", "id", "version", "created_at", "updated_at"})
|
||||
}
|
||||
// The profile fields of a request are the whole editable surface.
|
||||
for _, profile := range []struct {
|
||||
dto any
|
||||
want []string
|
||||
}{
|
||||
{api.OrganizationCreate{}, []string{"name", "description", "sphere", "contacts", "representatives"}},
|
||||
{api.OrganizationUpdate{}, []string{"expected_version", "name", "description", "sphere", "contacts", "representatives"}},
|
||||
} {
|
||||
typ, want := reflect.TypeOf(profile.dto), profile.want
|
||||
got := make([]string, 0, typ.NumField())
|
||||
for i := range typ.NumField() {
|
||||
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
|
||||
got = append(got, name)
|
||||
}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Errorf("%s fields = %v, want exactly %v", typ.Name(), got, want)
|
||||
}
|
||||
}
|
||||
// The candidate's card holds neither a member, a role, nor the ground
|
||||
// of the verification.
|
||||
assertNoJSONFields(t, api.CandidateOrganizationCard{}, []string{"role", "membership", "members", "verification", "basis", "version", "created_at", "updated_at", "user_id"})
|
||||
// The caller's own membership is the only place of a role, and it names
|
||||
// no account.
|
||||
assertNoJSONFields(t, api.OrganizationMembership{}, []string{"user_id", "account_id", "email"})
|
||||
// The list takes only the page, so no parameter names another account.
|
||||
params := reflect.TypeFor[api.ListMyOrganizationsParams]()
|
||||
names := make([]string, 0, params.NumField())
|
||||
for i := range params.NumField() {
|
||||
names = append(names, params.Field(i).Name)
|
||||
}
|
||||
if got := strings.Join(names, ","); got != "Limit,Cursor" {
|
||||
t.Fatalf("ListMyOrganizationsParams fields = %s, want only the page", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An update separates an absent list (unchanged) from an empty one (replaced
|
||||
// by an empty list) by nil, and null is not a list or an object.
|
||||
func TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart(t *testing.T) {
|
||||
var empty api.OrganizationUpdate
|
||||
if err := empty.UnmarshalJSON([]byte(`{"expected_version":1,"representatives":[]}`)); err != nil {
|
||||
t.Fatalf("decode an empty list: %v", err)
|
||||
}
|
||||
if empty.Representatives == nil || len(empty.Representatives) != 0 {
|
||||
t.Fatalf("representatives = %#v, want a non-nil empty slice", empty.Representatives)
|
||||
}
|
||||
|
||||
var absent api.OrganizationUpdate
|
||||
if err := absent.UnmarshalJSON([]byte(`{"expected_version":1}`)); err != nil {
|
||||
t.Fatalf("decode an absent list: %v", err)
|
||||
}
|
||||
if absent.Representatives != nil || absent.Name.IsSet() || absent.Contacts.IsSet() || absent.Description.IsSet() || absent.Sphere.IsSet() {
|
||||
t.Fatal("absent fields are set, want unset")
|
||||
}
|
||||
|
||||
var cleared api.OrganizationUpdate
|
||||
if err := cleared.UnmarshalJSON([]byte(`{"expected_version":1,"description":null,"sphere":"Платежи"}`)); err != nil {
|
||||
t.Fatalf("decode a null description: %v", err)
|
||||
}
|
||||
if !cleared.Description.IsSet() || !cleared.Description.IsNull() || !cleared.Sphere.IsSet() || cleared.Sphere.IsNull() {
|
||||
t.Fatal("description sent as null is not a set null, or the sphere is not a value")
|
||||
}
|
||||
|
||||
for _, body := range []string{
|
||||
`{"expected_version":1,"representatives":null}`,
|
||||
`{"expected_version":1,"name":null}`,
|
||||
`{"expected_version":1,"contacts":null}`,
|
||||
} {
|
||||
var null api.OrganizationUpdate
|
||||
if err := null.UnmarshalJSON([]byte(body)); err == nil {
|
||||
t.Fatalf("decode %s succeeded, want an error", body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The representatives of the candidate card are optional and nullable: absent
|
||||
// or null means that they are not published.
|
||||
func TestCandidateOrganizationCardRepresentativesAreOptional(t *testing.T) {
|
||||
const base = `"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО Пример","description":null,"sphere":null,"contacts":` + emptyOrganizationContacts + `,"verification_level":"e0"`
|
||||
for name, body := range map[string]string{
|
||||
"absent": "{" + base + "}",
|
||||
"null": "{" + base + `,"representatives":null}`,
|
||||
"empty": "{" + base + `,"representatives":[]}`,
|
||||
} {
|
||||
var card api.CandidateOrganizationCard
|
||||
if err := card.UnmarshalJSON([]byte(body)); err != nil {
|
||||
t.Fatalf("decode a card with %s representatives: %v", name, err)
|
||||
}
|
||||
if err := card.Validate(); err != nil {
|
||||
t.Fatalf("validate a card with %s representatives: %v", name, err)
|
||||
}
|
||||
}
|
||||
var withoutContacts api.CandidateOrganizationCard
|
||||
if err := withoutContacts.UnmarshalJSON([]byte(`{"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО","description":null,"sphere":null,"verification_level":"e0"}`)); err == nil {
|
||||
t.Fatal("decode a card without contacts succeeded, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
// The documented examples are valid values of the generated types, and the
|
||||
// organizations they show never claim a level above e0 on their own.
|
||||
func TestOrganizationExamplesAreValidResponsesAndNeverRaiseTheLevel(t *testing.T) {
|
||||
for _, name := range []string{"OrganizationNameOnly", "OrganizationCompleteCard"} {
|
||||
var organization api.Organization
|
||||
if err := organization.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
|
||||
t.Fatalf("decode the %s example: %v", name, err)
|
||||
}
|
||||
if err := organization.Validate(); err != nil {
|
||||
t.Fatalf("validate the %s example: %v", name, err)
|
||||
}
|
||||
if organization.Verification.Level != api.OrganizationVerificationLevelE0 || organization.Verification.Basis != api.OrganizationVerificationBasisConfirmedEmail ||
|
||||
organization.CandidateCard.VerificationLevel != api.OrganizationVerificationLevelE0 {
|
||||
t.Fatalf("%s example verification = %+v, want e0 on the confirmed email", name, organization.Verification)
|
||||
}
|
||||
if organization.CandidateCard.ID != organization.ID || organization.CandidateCard.Name != organization.Name {
|
||||
t.Fatalf("%s example card does not repeat the profile", name)
|
||||
}
|
||||
}
|
||||
var page api.MyOrganizationList
|
||||
if err := page.UnmarshalJSON(supportCaseExample(t, "MyOrganizationListPage")); err != nil {
|
||||
t.Fatalf("decode the MyOrganizationListPage example: %v", err)
|
||||
}
|
||||
if err := page.Validate(); err != nil {
|
||||
t.Fatalf("validate the MyOrganizationListPage example: %v", err)
|
||||
}
|
||||
for _, item := range page.Items {
|
||||
if item.Membership.State != api.MembershipStateActive || item.Membership.OrganizationID != item.Organization.ID {
|
||||
t.Fatalf("listed item %+v, want an active membership of the listed organization", item)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"OrganizationCreateNameOnly", "OrganizationCreateCompleteCard"} {
|
||||
var create api.OrganizationCreate
|
||||
if err := create.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
|
||||
t.Fatalf("decode the %s example: %v", name, err)
|
||||
}
|
||||
if err := create.Validate(); err != nil {
|
||||
t.Fatalf("validate the %s example: %v", name, err)
|
||||
}
|
||||
}
|
||||
var update api.OrganizationUpdate
|
||||
if err := update.UnmarshalJSON(supportCaseExample(t, "OrganizationUpdateCompleteCard")); err != nil {
|
||||
t.Fatalf("decode the OrganizationUpdateCompleteCard example: %v", err)
|
||||
}
|
||||
if err := update.Validate(); err != nil {
|
||||
t.Fatalf("validate the OrganizationUpdateCompleteCard example: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The contract enums list every level, basis, role, and state of the PRD now,
|
||||
// so adding one later is not a contract change. At the contract level, the
|
||||
// profile bodies are closed objects without a role or a level, and no
|
||||
// operation sets the verification level or a role.
|
||||
func TestOrganizationContractFollowsThePRD(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
for name, want := range map[string][]string{
|
||||
"OrganizationVerificationLevel": {"e0", "e1", "e2", "e3"},
|
||||
"OrganizationVerificationBasis": {"confirmed_email", "corporate_domain", "requisites_and_authority", "manual_review", "partner_status"},
|
||||
"OrganizationRole": {"owner", "recruiter", "hiring_manager", "technical_expert"},
|
||||
"MembershipState": {"active", "suspended", "removed", "left"},
|
||||
} {
|
||||
if got := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})); !slices.Equal(got, want) {
|
||||
t.Errorf("%s = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The requests are closed objects whose properties are the profile.
|
||||
for name, want := range map[string][]string{
|
||||
"OrganizationCreate": {"name", "description", "sphere", "contacts", "representatives"},
|
||||
"OrganizationUpdate": {"expected_version", "name", "description", "sphere", "contacts", "representatives"},
|
||||
} {
|
||||
schema := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
|
||||
if schema.AdditionalProperties == nil || schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
|
||||
t.Errorf("%s accepts unknown fields", name)
|
||||
}
|
||||
got := make([]string, 0, len(schema.Properties))
|
||||
for _, property := range schema.Properties {
|
||||
got = append(got, property.Name)
|
||||
}
|
||||
slices.Sort(got)
|
||||
sorted := slices.Clone(want)
|
||||
slices.Sort(sorted)
|
||||
if !slices.Equal(got, sorted) {
|
||||
t.Errorf("%s properties = %v, want %v", name, got, sorted)
|
||||
}
|
||||
}
|
||||
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationUpdate"})
|
||||
if !slices.Contains(update.Required, "expected_version") {
|
||||
t.Error("OrganizationUpdate does not require expected_version")
|
||||
}
|
||||
create := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationCreate"})
|
||||
if !slices.Equal(create.Required, []string{"name"}) {
|
||||
t.Errorf("OrganizationCreate required = %v, want only the name", create.Required)
|
||||
}
|
||||
|
||||
// Writing needs the CSRF token, and creating needs an Idempotency-Key.
|
||||
for _, id := range []string{"CreateOrganization", "UpdateOrganization"} {
|
||||
operation := operationByID(t, spec, id)
|
||||
if len(operation.Security) != 1 {
|
||||
t.Fatalf("%s security = %v, want one requirement", id, operation.Security)
|
||||
}
|
||||
if _, ok := operation.Security[0][sessionCSRFScheme]; !ok {
|
||||
t.Errorf("%s does not require the CSRF token", id)
|
||||
}
|
||||
}
|
||||
if !slices.ContainsFunc(operationByID(t, spec, "CreateOrganization").Parameters, func(parameter *ogen.Parameter) bool {
|
||||
return parameter.Ref == "#/components/parameters/IdempotencyKey"
|
||||
}) {
|
||||
t.Error("CreateOrganization does not require an Idempotency-Key")
|
||||
}
|
||||
if _, ok := operationByID(t, spec, "UpdateOrganization").Responses["412"]; !ok {
|
||||
t.Error("UpdateOrganization does not declare 412")
|
||||
}
|
||||
|
||||
// Nothing in the organization paths sets a verification level or a role.
|
||||
for path, item := range spec.Paths {
|
||||
if !strings.HasPrefix(path, "/api/v1/organizations") && path != myOrganizationsPath {
|
||||
continue
|
||||
}
|
||||
for _, operation := range []*ogen.Operation{item.Get, item.Post, item.Put, item.Patch, item.Delete} {
|
||||
if operation == nil {
|
||||
continue
|
||||
}
|
||||
id := strings.ToLower(operation.OperationID)
|
||||
if strings.Contains(id, "verification") || strings.Contains(id, "verify") || strings.Contains(id, "role") || strings.Contains(id, "promote") {
|
||||
t.Errorf("%s %s sets a level or a role", path, operation.OperationID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user