Documentation
¶
Overview ¶
Package fakegraph is a stateful, in-memory Microsoft Graph server for the teams CLI test suite. It is an httptest.Server plus a seeded store, so a test can exercise the real internal/graph client (and later the testscript end-to-end scripts) without a tenant.
srv := fakegraph.New(t, fakegraph.Options{
Model: fakegraph.Model{
Me: "u-me",
Users: []fakegraph.User{{ID: "u-me", DisplayName: "Me"}, {ID: "u-alice", DisplayName: "Alice"}},
Teams: []fakegraph.Team{{
ID: "t-eng", DisplayName: "Engineering",
Channels: []fakegraph.Channel{{ID: "c-general", DisplayName: "General"}},
}},
},
})
client, _ := graph.New(graph.Options{BaseURL: srv.URL(), Token: graph.TokenSourceFunc(...)})
Fidelity ¶
The endpoints, query limits and error shapes mirror the vendored api-reference and concepts pages under refs/graph (cited per handler), with the live-observed corrections from docs/spike/phase1.md applied wherever the two disagree. The places where the spike overrides the docs are marked "spike-observed" throughout the package.
In particular:
- `@odata.nextLink` paging is served on every collection that pages, with the documented caps: `$top` > 50 is a 400 for channel messages, replies and chat messages, and `/me/chats` (refs/graph/api-reference/v1.0/api/channel-list-messages.md:35, chatmessage-list-replies.md:30, chat-list-messages.md:32, chat-list.md:31; docs/spike/phase1.md:52-58);
- team and channel member lists default to 100 and cap at 999, and they do page — the spike saw `@odata.nextLink` at `$top=5` where the docs imply no paging (refs/graph/api-reference/v1.0/api/team-list-members.md:30, docs/spike/phase1.md:50);
- `$expand=replies` inlines up to 200 replies per root and offers the rest through `replies@odata.nextLink` (refs/graph/api-reference/v1.0/api/channel-list-messages.md:37-38);
- `$filter` on channel messages is rejected with 400, never silently ignored (docs/spike/phase1.md:53);
- chat message lists implement the documented `$orderby`/`$filter` matrix, including the rule that a `$filter` is ignored unless a matching `$orderby` is present, while `lastModifiedDateTime gt` works either way and a default listing is deliberately unsorted (refs/graph/api-reference/v1.0/api/chat-list-messages.md:33-34; docs/spike/phase1.md:60-65);
- `POST /search/query` pages by `from`/`size` with no `@odata.nextLink`, reports the full match count in `total`, honours `size` up to 50 for chatMessage, returns 500 for the documented-but-broken `IsRead` term and never returns message bodies (docs/spike/phase1.md:75-83);
- `/chats/{id}/softDelete` and a standalone hostedContents POST answer 405, because that is what the live service does (docs/spike/phase1.md:91,99; PLAN.md "Chat quirks");
- `$batch` enforces the documented maximum of 20, unique ids and the rule that sub-request failures travel inside a 200 outer response (refs/graph/concepts/json-batching.md:17,48,119).
Authorization ¶
Every route declares the delegated scope it needs. The grant comes from Options.Scopes or, when that is nil, from the `scp` claim of the bearer token the request carries (the spike confirmed `scp` lists every admin-consented scope, docs/spike/phase1.md:17). A missing scope is a 403 `Authorization_RequestDenied` whose message names the scope, so the CLI's scope pre-check and its 403 handling are both testable. Scopes that config.DelegatedAdminConsentScopes marks as needing admin consent are only granted when Options.AdminConsentedScopes says they were consented.
Index ¶
- Constants
- Variables
- func BatchContract(body []byte) error
- func MeetingThreadID(eventID string) string
- func StandardBase64(restID string) string
- func Token(scopes ...string) string
- func TokenFor(userID string, scopes ...string) string
- type Attachment
- type CalendarEvent
- type Channel
- type Chat
- type ContractHook
- type ContractReporter
- type ContractValidator
- type Drive
- type DriveItem
- type Fault
- func ExpiredToken(method, path string, call int, challenge bool) Fault
- func ForbiddenScope(method, path string, call int, scope string) Fault
- func Malformed(method, path string, call int, body string) Fault
- func Slow(method, path string, call int, delay time.Duration) Fault
- func Throttle(method, path string, call, retryAfter int) Fault
- func Unavailable(method, path string, call int) Fault
- type HostedContent
- type Member
- type Mention
- type Message
- type Model
- type Options
- type Reaction
- type RecordedRequest
- type Server
- func (s *Server) BaseURL() string
- func (s *Server) Client() *http.Client
- func (s *Server) Clock() clock.Clock
- func (s *Server) Close()
- func (s *Server) Handler() http.Handler
- func (s *Server) Implements(method, template string) bool
- func (s *Server) LastRequest() *RecordedRequest
- func (s *Server) Me() string
- func (s *Server) Requests() []*RecordedRequest
- func (s *Server) RequestsFor(method, path string) []*RecordedRequest
- func (s *Server) ResetRequests()
- func (s *Server) Routes() []string
- func (s *Server) Seed(m Model)
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) URL() string
- type StaleSearchHit
- type Team
- type User
Constants ¶
const ( // DefaultBasePath is the Graph service root's version segment. DefaultBasePath = "/v1.0" // DefaultSearchPageSize is the documented default `size` of a search // request (refs/graph/api-reference/v1.0/resources/search-api-overview.md:63). DefaultSearchPageSize = 25 // DefaultMaxBodyBytes caps how much of a request body the fake buffers. DefaultMaxBodyBytes = 8 << 20 )
Defaults for Options.
const ( ChatTypeOneOnOne = "oneOnOne" ChatTypeGroup = "group" ChatTypeMeeting = "meeting" )
Chat types Graph documents (refs/graph/api-reference/v1.0/resources/chat.md, "chatType values"). There is no "self" member: the self chat is the one-on-one chat whose only member is the signed-in user, with the documented id 48:notes.
const ( ChannelStandard = "standard" ChannelPrivate = "private" )
Channel membership types Graph documents (refs/graph/api-reference/v1.0/resources/channel.md, "channelMembershipType values").
const ( // CalendarAccessNone is a calendar that is not shared at all: the calendar // view answers 403 ErrorAccessDenied and the CLI falls back to free/busy. CalendarAccessNone = "none" // CalendarAccessFreeBusy is a calendar shared as free/busy only, which the // live tenant answered with 404 ErrorItemNotFound rather than 403. CalendarAccessFreeBusy = "freeBusy" // CalendarAccessRead is a calendar shared in full, so /users/{id}/calendarView // returns the events. CalendarAccessRead = "read" )
Calendar access levels, as Model.CalendarAccess values.
const ( // CalendarEventTimed is a normal timed event. CalendarEventTimed = "timed" // CalendarEventAllDay is a floating all-day event: Graph always returns it // as 00:00:00 to 00:00:00 on its own dates, whatever zone was requested // (plans/calendar.md §3, F5). CalendarEventAllDay = "allDay" )
Calendar event kinds, as CalendarEvent.Kind values.
const DefaultCalendarViewTop = 10
DefaultCalendarViewTop is the calendarView page size when the caller sends no $top. The documented default is 10, which is why the CLI always sends $top=100 (plans/calendar.md §3, F2).
const DefaultMe = "me"
DefaultMe is the id of the signed-in user when a seed does not name one.
const ( // DefaultMyDriveID is the id GET /me/drive reports when the seed does not // name one. DefaultMyDriveID = "drive-me" )
Default values applied by [Model.withDefaults].
const DefaultTenantID = "11111111-1111-1111-1111-111111111111"
DefaultTenantID is the tenant id stamped on teams, channels and chats.
const MaxCalendarViewTop = 1000
MaxCalendarViewTop is the largest $top the fake accepts, matching the live service's acceptance of 1000 (plans/calendar.md §3, F2).
const MaxSearchSize = 50
MaxSearchSize is the largest `size` the fake honours for chatMessage. The spike observed 50 working and the docs cap `message` at 25, so 50 is the live behaviour (docs/spike/phase1.md:75).
const MethodNotAllowed = http.StatusMethodNotAllowed
MethodNotAllowed is the status the fake returns for a path that exists with a different method. It is exported so tests can assert the documented 405 cases (docs/spike/phase1.md:91,99) without magic numbers.
const PreferUnknownEnumMembers = "include-unknown-enum-members"
PreferUnknownEnumMembers is the Prefer value the internal/graph client sends.
const ( // RepliesExpandedMax is how many replies `$expand=replies` inlines before // it hands the rest to replies@odata.nextLink // (refs/graph/api-reference/v1.0/api/channel-list-messages.md:37). RepliesExpandedMax = 200 )
Page-size limits. The message, reply and chat caps are documented (50) and the spike confirmed the 400 (refs/graph/api-reference/v1.0/api/channel-list-messages.md:35, chatmessage-list-replies.md:30, chat-list-messages.md:32, chat-list.md:31; docs/spike/phase1.md:52,56,58). Member lists default to 100 and cap at 999 (refs/graph/api-reference/v1.0/api/team-list-members.md:30, channel-list-members.md:29); the spike saw them page even at `$top=5` (docs/spike/phase1.md:50). The directory collections use the same 100/999 window (refs/graph/api-reference/v1.0/api/user-list.md:36).
const SelfChatID = "48:notes"
SelfChatID is the documented id of the "chat with yourself" chat (docs/spike/phase1.md:103; PLAN.md "Smart references").
Variables ¶
var DefaultOnlineMeetingProviders = []string{"teamsForBusiness"}
DefaultOnlineMeetingProviders is the allowedOnlineMeetingProviders list a mailbox reports unless the seed overrides it. It contains teamsForBusiness, so `teams calendar create --teams` succeeds by default; seed a User with a list without that entry to exercise the mailbox that silently ignores isOnlineMeeting (plans/calendar.md §3, F10).
Functions ¶
func BatchContract ¶
BatchContract validates a recorded /$batch request body with the local batch schema, because the Graph description has no batch path or schema (PLAN.md Layer 6). A test calls it with the body the recorder captured.
func MeetingThreadID ¶ added in v1.1.0
MeetingThreadID derives the deterministic chat thread id the fake serves for a meeting, in the documented 19:meeting_…@thread.v2 form (refs/graph/api-reference/v1.0/resources/chatinfo.md).
func StandardBase64 ¶ added in v1.1.0
StandardBase64 encodes a REST event id the way the search service reports a hitId: base64 in the STANDARD alphabet, so the result can contain "/" and "+".
The id itself is not encoded — a Graph event id already is a base64 string — so this is the identity for a REST id that has no "/" or "+" and a two-character substitution for one that has. `internal/graph.EventIDFromHitID` performs the reverse swap, which is the whole conversion (plans/calendar.md §3, F8).
Modelling it faithfully matters: an earlier version of this helper base64-encoded the id *string* while the CLI decoded it, so the two agreed with each other and neither agreed with the service, and `calendar search` returned nothing on a real tenant while every fake-backed test passed.
Types ¶
type Attachment ¶
type Attachment struct {
ID string
Name string
ContentType string
ContentURL string
Content string
ThumbnailURL string
TeamsAppID string
}
Attachment is a chatMessageAttachment (refs/graph/api-reference/v1.0/resources/chatmessageattachment.md).
type CalendarEvent ¶ added in v1.1.0
type CalendarEvent struct {
// ID defaults to "event-<n>".
ID string
// OwnerID is the mailbox the event lives in; "" means [Model.Me].
OwnerID string
// Subject is the event subject.
Subject string
// Kind defaults to [CalendarEventTimed].
Kind string
// Start and End are the event's instants, in any location.
Start time.Time
End time.Time
// Days is the length in days of an all-day event. Zero means one day.
Days int
// ShowAs defaults to "busy".
ShowAs string
// IsCancelled marks a cancelled event, which the CLI hides unless
// --include-cancelled.
IsCancelled bool
// OrganizerName is the organizer's display name; "" means the owner.
OrganizerName string
// IsOrganizer marks the event as organized by the mailbox owner, which is
// what the Phase 6b pre-checks read.
IsOrganizer bool
// AllowNewTimeProposals is the Phase 6b pre-check field; nil means the
// documented default of true.
AllowNewTimeProposals *bool
// Location is the location display name.
Location string
// Teams marks a Teams online meeting. It sets isOnlineMeeting,
// onlineMeetingProvider and onlineMeeting.joinUrl.
Teams bool
// JoinURL overrides the generated join URL for a Teams meeting.
JoinURL string
// Response is the signed-in user's responseStatus.response.
Response string
// Type defaults to "singleInstance".
Type string
// SeriesMasterID is set when the event is part of a recurring series.
SeriesMasterID string
// WebLink overrides the generated webLink.
WebLink string
// NoMailbox makes every calendar lookup for this event's owner answer as if
// the mailbox were missing, without touching the owner's User entry.
NoMailbox bool
// contains filtered or unexported fields
}
CalendarEvent is one seeded calendar event.
Start and End are instants for a timed event and the event's own dates for an all-day one; [Model.withDefaults] converts the latter from CalendarEvent.Start and CalendarEvent.End (or CalendarEvent.Days).
type Channel ¶
type Channel struct {
ID string
DisplayName string
Description string
// MembershipType defaults to [ChannelStandard].
MembershipType string
Created time.Time
// Members defaults to the team members when empty.
Members []Member
// Messages are root messages; each may carry Replies.
Messages []Message
// DriveID and FilesFolderID override the filesFolder this channel points
// at. When empty the fake derives DriveID "drive-<teamID>" and
// FilesFolderID "folder-<channelID>" and creates that folder, so
// GET /teams/{id}/channels/{id}/filesFolder works without extra seeding.
DriveID string
FilesFolderID string
}
Channel is a channel (standard, private or shared) with its root messages.
type Chat ¶
type Chat struct {
ID string
// ChatType defaults to [ChatTypeGroup]; use [ChatTypeOneOnOne] for a 1:1
// chat. A chat whose members are exactly the signed-in user is the self
// chat; seed it with the id [SelfChatID].
ChatType string
Topic string
Created time.Time
Updated time.Time
// Members defaults to the signed-in user when empty.
Members []Member
// Messages are the chat messages, oldest first in the seed.
Messages []Message
// LastRead seeds viewpoint.lastMessageReadDateTime for the signed-in user.
LastRead time.Time
// Hidden seeds viewpoint.isHidden.
Hidden bool
// Deleted seeds a soft-deleted chat (softDelete), which stays readable but
// is hidden from /me/chats.
Deleted bool
}
Chat is a one-on-one, group or meeting chat.
type ContractHook ¶
type ContractHook struct {
// contains filtered or unexported fields
}
ContractHook validates traffic against the trimmed OpenAPI description that internal/testing/contract embeds.
func NewContractHook ¶
func NewContractHook(v ContractValidator, r ContractReporter) *ContractHook
NewContractHook is the injectable form of WithContract, for a validator that is not the embedded one.
func WithContract ¶
func WithContract(t testing.TB) *ContractHook
WithContract returns an Options.Contract hook backed by the Layer 6 validator. Install it like this:
srv := fakegraph.New(t, fakegraph.Options{Contract: fakegraph.WithContract(t)})
Every request the fake serves (including /$batch sub-requests) and every response it returns is then checked against the spec, and a failure is reported with t.Errorf rather than panicking mid-request.
type ContractReporter ¶
ContractReporter is the testing handle a hook reports through.
type ContractValidator ¶
type ContractValidator interface {
ValidateRequest(method, path string, query url.Values, body []byte) error
ValidateResponse(method, path string, status int, body []byte) error
}
ContractValidator is the validator surface ContractHook needs. It is an interface so the fake's behaviour does not depend on kin-openapi types and so a test can substitute a recording stub.
type DriveItem ¶
type DriveItem struct {
ID string
Name string
ParentID string
Folder bool
Content []byte
ContentType string
Created time.Time
Modified time.Time
WebURL string
}
DriveItem is a file or folder. ParentID "" means the drive root; the root item itself is created automatically with the id "root".
type Fault ¶
type Fault struct {
// Method matches the HTTP method; "" matches every method.
Method string
// Path matches the Graph path relative to the service root (for example
// "/me/chats"), with an optional trailing "*" prefix match; "" matches
// every path.
Path string
// Call is the 1-based index among matching requests, or 0 for all.
Call int
// Status is the response status; 0 means "do not fail, only delay".
Status int
// Code overrides the error envelope's code.
Code string
// Message overrides the error envelope's message.
Message string
// RetryAfter sets the Retry-After header in seconds. It is what the
// throttling doc tells clients to honour
// (refs/graph/concepts/throttling.md:53-72).
RetryAfter int
// ClaimChallenge adds the CAE WWW-Authenticate claims challenge to a 401,
// which is how Graph reports a token that CAE revoked
// (refs/entra/docs/identity-platform/app-resilience-continuous-access-evaluation.md:35-41).
ClaimChallenge bool
// MalformedJSON returns Body as-is (or a truncated fragment) instead of a
// valid response.
MalformedJSON bool
// Body overrides the raw response body.
Body string
// Delay delays the response without failing (a slow response).
Delay time.Duration
}
Fault injects one failure into the fake.
Selector: Method and Path (both optional) match a request; Path supports a trailing "*" for a prefix match. Call selects which matching request the fault fires on, counting from 1; 0 means every matching request.
Effect: Status writes the status with a Graph error envelope; a Delay-only fault (Status 0, MalformedJSON false) waits and then serves the real response; MalformedJSON returns Body (or a truncated JSON fragment) as the response body.
func ExpiredToken ¶
ExpiredToken returns a 401 fault for an expired access token. With challenge set it also carries the CAE WWW-Authenticate claims challenge.
func ForbiddenScope ¶
ForbiddenScope returns a 403 fault naming the scope the CLI is missing.
func Malformed ¶
Malformed returns a response whose body is not valid JSON, so the client's decoder fails.
func Unavailable ¶
Unavailable returns a 503 fault. Graph does not document 503 as retryable (refs/INDEX.md:180), so the CLI treats it as transport-level safety only.
type HostedContent ¶
HostedContent is an inline image. ID is the id the body reference uses; for an inbound POST it is the body's @microsoft.graph.temporaryId, which must equal the id in ../hostedContents/{id}/$value (refs/INDEX.md, "Inline images have no create endpoint in the v1.0 API reference"; docs/spike/phase1.md:90).
type Member ¶
Member is a conversation member. Roles are the documented strings: "owner", "guest" or empty for a plain member (refs/graph/api-reference/v1.0/resources/conversationmember.md).
type Mention ¶
type Mention struct {
ID int
Text string
UserID string
UserDisplayName string
UserIdentityType string
}
Mention is a chatMessageMention. The <at id="N"> tag in the body must match ID (refs/graph/api-reference/v1.0/resources/chatmessagemention.md).
type Message ¶
type Message struct {
ID string
AuthorID string
Body string
ContentType string
Subject string
Summary string
// Importance defaults to "normal" (normal, high or urgent).
Importance string
// MessageType defaults to "message"; set it to "systemEventMessage" to
// exercise the Prefer: include-unknown-enum-members behaviour, where
// Graph reports unknownFutureValue without that header
// (docs/spike/phase1.md:54).
MessageType string
Locale string
Created time.Time
Modified time.Time
Edited time.Time
Deleted time.Time
Attachments []Attachment
Mentions []Mention
Reactions []Reaction
// HostedContents are seeded inline images. CreatedAt defaults to Created.
HostedContents []HostedContent
// EventDetail is the raw eventDetail object of a systemEventMessage.
EventDetail string
// Replies are the replies of a channel root message.
Replies []Message
}
Message is a channel message, chat message or reply. ID and Body are the only fields a caller normally sets; everything else has a documented default.
type Model ¶
type Model struct {
// Me is the signed-in user id; it defaults to [DefaultMe]. If no user
// with that id is seeded, a user is created for it.
Me string
// Users are the directory users.
Users []User
// Teams carry their channels and channel messages.
Teams []Team
// Chats carry their members and messages.
Chats []Chat
// Drives carry drive items (files and folders).
Drives []Drive
// CalendarEvents are the seeded calendar events, keyed by the mailbox owner
// they belong to. An event with OwnerID "" belongs to [Model.Me], whose
// calendar is always readable by the signed-in user.
//
// The calendar routes reproduce the behaviour the handoff verified live on
// 2026-10-05 (plans/calendar.md §3): a 1825-day calendarView window, an
// onlineMeeting that is dropped unless isOnlineMeeting is selected, floating
// all-day events, a 62-day getSchedule window, a null scheduleItems plus a
// "5016" error, and the /users/{id}/calendarView access failures.
CalendarEvents []CalendarEvent
// StaleSearchHits are event ids the search index still returns but whose event
// no longer exists. The live service does exactly this — a deleted event stays
// in the index for a while — and it is the case that makes a hit unreadable,
// so a test can exercise the CLI's "N search hit(s) could not be read"
// warning. Each entry is `{ID, Subject}`: the subject is only used to decide
// whether the hit matches a query.
StaleSearchHits []StaleSearchHit
// CalendarAccess says how the signed-in user may see another user's
// calendar. The key is the owner's user id and the value is one of the
// [CalendarAccessNone], [CalendarAccessFreeBusy] or [CalendarAccessRead]
// constants; a missing entry means "not shared", which is the 403
// ErrorAccessDenied case.
CalendarAccess map[string]string
// MyDriveID is the drive GET /me/drive reports, which is where a chat file
// attachment is uploaded (refs/teams-mcp/src/utils/file-upload.ts:256). It
// defaults to [DefaultMyDriveID]; seed a Drive with that id to give the
// user's drive pre-existing items.
MyDriveID string
}
Model is the seed for a fake server.
srv := fakegraph.New(t, fakegraph.Options{
Model: fakegraph.Model{
Users: []fakegraph.User{{ID: "u1", DisplayName: "Alice"}},
Teams: []fakegraph.Team{{
ID: "t1", DisplayName: "Engineering",
Channels: []fakegraph.Channel{{
ID: "c1", DisplayName: "General",
Messages: []fakegraph.Message{{ID: "m1", AuthorID: "u1", Body: "<p>hi</p>"}},
}},
}},
},
})
Additional state can be merged later with Server.Seed.
type Options ¶
type Options struct {
// Model is the seed. It is deterministic by construction.
Model Model
// Clock supplies timestamps for objects created through the API
// (messages, chats, reactions, read state). Seed data never uses it, so a
// test is reproducible as long as it injects a frozen clock here.
Clock clock.Clock
// TenantID is stamped on teams, channels, members and chats.
TenantID string
// BasePath is the service root's version segment; it defaults to
// [DefaultBasePath] and must start with "/".
BasePath string
// Scopes, when non-nil, is the authoritative scope grant. When nil, the
// grant is read from the bearer token's `scp` claim; with no token either,
// it defaults to every scope in every config preset plus the incremental
// scopes, so a test that does not care about authorization needs no setup.
Scopes []string
// AdminConsentedScopes gates config.DelegatedAdminConsentScopes: only the
// listed scopes are granted. When nil, every admin-consent scope is
// treated as consented (the permissive default described in the package
// doc); pass a list to exercise the consent failure path.
AdminConsentedScopes []string
// RequireToken makes a missing or undecodable bearer token a 401. The
// default is permissive, because most tests do not exercise
// authentication.
RequireToken bool
// ScopesFromTokenOnly makes the grant come strictly from the bearer token's
// scp claim, so a request that needs a scope the token does not carry is a
// 403 instead of being covered by the permissive default. The CLI's own
// tests use it against a TEAMS_ACCESS_TOKEN, where the CLI skips its own
// pre-check.
ScopesFromTokenOnly bool
// Faults inject failures per route and call index.
Faults []Fault
// SearchPageSize overrides the default search page size.
SearchPageSize int
// ChatMembersExpandCap caps the members an `$expand=members` chat list
// returns. The docs give 25; the spike saw 116 members with no cap, so the
// default is 0 (no cap) and the documented behaviour is one option away
// (refs/graph/api-reference/v1.0/api/chat-list.md:31,
// docs/spike/phase1.md:59).
ChatMembersExpandCap int
// MaxBodyBytes caps request-body buffering; it defaults to
// [DefaultMaxBodyBytes].
MaxBodyBytes int64
// Contract, when set, validates every request and response against the
// Layer 6 trimmed Graph OpenAPI description. Use [WithContract] to build
// it; see contract.go.
Contract *ContractHook
}
Options configures a fake Graph server.
type Reaction ¶
Reaction is a chatMessageReaction (refs/graph/api-reference/v1.0/resources/chatmessagereaction.md).
type RecordedRequest ¶
type RecordedRequest struct {
// Seq is the 1-based arrival order across the server's lifetime.
Seq int
// Method is the HTTP method.
Method string
// Path is the Graph path relative to the service root, for example
// "/me/chats" or "/teams/t1/channels/c1/messages".
Path string
// RawPath is the path as it arrived, including the version segment.
RawPath string
// Query holds the decoded query parameters.
Query url.Values
// Header holds the request headers.
Header http.Header
// Body is the raw request body.
Body []byte
// Sub marks a /$batch sub-request.
Sub bool
// Status is the response status code.
Status int
// Response is the raw response body.
Response []byte
}
RecordedRequest is one request the fake saw, with the response it produced. The recorder exists so tests can assert the exact payloads the CLI sends: mention `<at id="N">` tags, `hostedContents[]` with its `@microsoft.graph.temporaryId`, and attachment references (PLAN.md Layer 2).
func (*RecordedRequest) BodyString ¶
func (rr *RecordedRequest) BodyString() string
BodyString returns the request body as a string, for substring assertions on mention tags or attachment references.
func (*RecordedRequest) DecodeBody ¶
func (rr *RecordedRequest) DecodeBody(v any) error
DecodeBody unmarshals the request body into v.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a running fake Graph server. Create it with New (which closes it with t.Cleanup) or NewServer (which the caller closes).
func (*Server) Client ¶
Client returns the HTTP client the underlying httptest server suggests. It is the default client; it exists so callers do not need to know the fake is an httptest.Server.
func (*Server) Close ¶
func (s *Server) Close()
Close shuts the server down. New registers it with t.Cleanup.
func (*Server) Handler ¶
Handler returns the underlying http.Handler so the dev server and the testscript parent process can mount it.
func (*Server) Implements ¶
Implements reports whether the fake serves an api-reference route template such as "GET /teams/{team-id}/channels/{channel-id}/messages" (the shape contract.Routes returns). Callers use it to decide whether a committed route is worth exercising or should be skipped with a reason.
func (*Server) LastRequest ¶
func (s *Server) LastRequest() *RecordedRequest
LastRequest returns the most recent recorded request, or nil.
func (*Server) Requests ¶
func (s *Server) Requests() []*RecordedRequest
Requests returns every recorded request in arrival order.
func (*Server) RequestsFor ¶
func (s *Server) RequestsFor(method, path string) []*RecordedRequest
RequestsFor returns the recorded requests whose method and Graph path match. Query parameters are ignored, so a test can find "/me/chats" whatever the $top was.
func (*Server) ResetRequests ¶
func (s *Server) ResetRequests()
ResetRequests clears the recorder without touching the seed. It is useful in a long test that asserts on one call at a time.
func (*Server) Routes ¶
Routes returns the fake's real route surface as "METHOD /pattern" lines, sorted, excluding the 405 placeholders and the fake-only download and upload URLs. It is the counterpart to contract.Routes and lets a test compare the two lists.
func (*Server) Seed ¶
Seed merges more state into the running server. It panics on an invalid model, because a broken seed is a test bug.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*Server) URL ¶
URL is the Graph service root including the version segment, for example http://127.0.0.1:41234/v1.0. Pass it to graph.Options.BaseURL.
type StaleSearchHit ¶ added in v1.1.0
type StaleSearchHit struct {
// ID is the event id the index still holds, in the REST (URL-safe) spelling.
ID string
// Subject is what the index has for the hit, used to match a query.
Subject string
}
StaleSearchHit is one search-index entry whose event no longer exists. See Model.StaleSearchHits.
type Team ¶
type Team struct {
ID string
DisplayName string
Description string
// Visibility defaults to "public".
Visibility string
Created time.Time
// Members defaults to the signed-in user as owner when empty.
Members []Member
Channels []Channel
}
Team is a team with its channels.
type User ¶
type User struct {
ID string
DisplayName string
GivenName string
Surname string
UserPrincipalName string
Mail string
JobTitle string
Department string
OfficeLocation string
PreferredLanguage string
// Relevance orders this user in /me/people: the higher the score, the
// earlier the person appears. The People API is documented as "ordered by
// relevance … determined by the user's communication and collaboration
// patterns" (refs/graph/api-reference/v1.0/api/user-list-people.md:12).
Relevance float64
// NoMailbox marks a user that exists but has no Exchange Online mailbox.
// /users/{id}/calendarView then answers 404 MailboxNotEnabledForRESTAPI and
// getSchedule answers a "5016" per-schedule error, which is the pair of
// cases the handoff could not tell apart with only one mailbox missing
// (plans/calendar.md §3, F4 and F7).
NoMailbox bool
// OnlineMeetingProviders is the mailbox's allowedOnlineMeetingProviders,
// which GET /me/calendar reports. It defaults to
// [DefaultOnlineMeetingProviders]; set it to a list without
// "teamsForBusiness" to exercise the silently-dropped Teams meeting
// (plans/calendar.md §3, F10).
OnlineMeetingProviders []string
}
User is a directory user.
Source Files
¶
- auth.go
- chatquery.go
- contract.go
- errors.go
- fakegraph.go
- faults.go
- handlers.go
- handlers_batch.go
- handlers_calendar.go
- handlers_calendar_write.go
- handlers_chats.go
- handlers_files.go
- handlers_messages.go
- handlers_search.go
- handlers_teams.go
- handlers_users.go
- model.go
- paging.go
- queryoptions.go
- recorder.go
- routes.go
- store.go
- types.go