graphmock

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package graphmock provides a typed fake Microsoft Graph endpoint for tests.

Handlers return Go values rather than JSON strings, so a response is built through the same marshaling the production code uses. A hand-written string literal cannot drift-check against a model: rename a field or change a tag and the literal keeps parsing, so the test keeps passing while the code is wrong.

The second purpose matters more. A fake that agrees with everything is a mirror, not a test. Real Graph refuses filters that OData permits, pages delta far smaller than callers expect, and omits headers callers assume are there. ExchangeMail encodes those refusals, so a request the service would reject is rejected here too, at the speed of a unit test.

Index

Constants

View Source
const (
	// TeamsChatPageCap is the largest page the chat listing serves.
	TeamsChatPageCap = 50
	// TeamsMessagePageCap is the largest page a chat or channel message
	// listing serves.
	TeamsMessagePageCap = 50
	// TeamsChannelMessageDefaultPageSize is what a channel message listing
	// returns when $top says nothing, which is well under the cap.
	TeamsChannelMessageDefaultPageSize = 20
	// TeamsExpandedMemberCap is how many members $expand=members returns,
	// however many the chat has and whatever $top asks for. There is no
	// continuation link for the rest.
	TeamsExpandedMemberCap = 25
	// TeamsExpandedReplyCap is how many replies $expand=replies returns
	// before paging the remainder through a per-message link.
	TeamsExpandedReplyCap = 200
	// TeamsSearchPageCap is the largest message search page.
	TeamsSearchPageCap = 25
)

Page and expansion limits the Teams endpoints apply.

None of these is announced. Every one is a number the service silently substitutes for whatever was asked, so a caller that gets exactly this many items cannot tell a truncated answer from a complete one.

View Source
const ExchangeCalendarPageCap = 1000

ExchangeCalendarPageCap is the largest page Exchange returns for a calendar view, whatever odata.maxpagesize asks for.

View Source
const ExchangeMailDeltaDefaultPageSize = 10

ExchangeMailDeltaDefaultPageSize is how many messages a delta query returns when no page size is requested. It is small enough that walking a large mailbox without asking for more takes tens of thousands of requests.

View Source
const ExchangeMailPageCap = 512

ExchangeMailPageCap is the largest page Exchange will return for mail, whatever odata.maxpagesize asks for.

Variables

View Source
var ExchangeMailSortableFields = []string{
	"isRead",
	"isDraft",
	"receivedDateTime",
	"sentDateTime",
	"categories",
}

ExchangeMailSortableFields are the message properties Exchange will filter on while also sorting. Filtering on anything else alongside an $orderby is refused, because no index serves both at once.

View Source
var TeamsMessageSortableFields = []string{"createdDateTime", "lastModifiedDateTime"}

TeamsMessageSortableFields are the only two properties a message listing will order by. Both are timestamps, and neither can be ordered ascending.

View Source
var WindowsTimeZones = []string{
	"Pacific Standard Time",
	"Eastern Standard Time",
	"GMT Standard Time",
	"W. Europe Standard Time",
	"Tokyo Standard Time",
	"E. South America Standard Time",
}

WindowsTimeZones are the names Graph uses when a request asks for a zone. None is an IANA name, so none resolves through Go's time package: a client that assumes otherwise computes the wrong instant without an error anywhere.

Functions

func Decode

func Decode[T any](tb testing.TB, r *Request) T

Decode unmarshals the request body into v, failing the test if it cannot.

Types

type Constraint

type Constraint func(*Request) *Response

A Constraint inspects a request and returns a rejection, or nil to let it through. Constraints exist so the fake refuses what the real service refuses: every one here was established by running the request against a live mailbox and reading the error back.

func CapPageSize

func CapPageSize(maxSize int) Constraint

CapPageSize truncates an oversized odata.maxpagesize request rather than failing it, which is what Graph does.

func CapTop added in v0.13.0

func CapTop(pathFragment string, maxTop int) Constraint

CapTop clamps an oversized $top on any path containing the fragment, the way Teams does.

It is a clamp and not a rejection because the service serves fewer items without comment. A caller that asked for two hundred and received fifty has no way to distinguish that from a chat holding fifty messages, which is why a client needs to be told the number it asked for was not honored rather than inferring completeness from a short page.

func ExchangeCalendar added in v0.10.0

func ExchangeCalendar() []Constraint

ExchangeCalendar returns the constraints a real Outlook calendar applies.

The calendar rules differ from the mail ones in kind, not just in detail: a calendar view is a distinct resource with required parameters rather than a filtered collection, and getting that wrong produces an empty or wrong answer rather than an error.

func ExchangeMail

func ExchangeMail() []Constraint

ExchangeMail returns the constraints a real Outlook mailbox applies.

Using these turns a class of production-only failure into a test failure: a filter Exchange cannot serve is rejected here with the same error code.

func ExchangeOutlook added in v0.11.0

func ExchangeOutlook() []Constraint

ExchangeOutlook returns the constraints that apply across an Outlook mailbox, beyond the mail and calendar sets.

Each one here was a bug before it was a constraint. The service does not refuse these in a way anyone would guess, so a fake that answered optimistically let the mistake through and the suite stayed green.

func IgnoreMismatchedMessageFilter added in v0.13.0

func IgnoreMismatchedMessageFilter() Constraint

IgnoreMismatchedMessageFilter drops a $filter that names a property the $orderby does not, the way a Teams message listing does.

This is the most dangerous behavior in the Teams API and the reason this bundle exists. The service does not refuse the request and does not warn: it discards the filter and answers the whole collection, successfully. A caller asking for the last day of a chat gets a year of it and renders the lot as today. A filter with no $orderby at all is discarded the same way.

So this drops the filter rather than rejecting the request. Rejecting would be easier to test against and would be fiction -- a failure mode production never exhibits -- and a client written against a fake that refuses would still be wrong against the service that does not.

func RejectAscendingMessageSort added in v0.13.0

func RejectAscendingMessageSort() Constraint

RejectAscendingMessageSort refuses an ascending order on a message listing.

Descending is the only direction served. This one the service does refuse, so a caller wanting oldest-first has to page the whole range and reverse it -- worth discovering in a test rather than after building a transcript view around an ordering that does not exist.

func RejectFilterOnCalendarView added in v0.10.0

func RejectFilterOnCalendarView() Constraint

RejectFilterOnCalendarView refuses a $filter on start or end in a calendar view.

The window is what selects events; expressing it as a filter as well is a misunderstanding the service does not correct, because it silently ignores the filter and returns the whole window.

func RejectRecipientLambdas

func RejectRecipientLambdas() Constraint

RejectRecipientLambdas refuses any/all over a recipient collection, which Exchange answers with ErrorInvalidUrlQueryFilter however it is written.

func RejectSearchSort added in v0.13.0

func RejectSearchSort() Constraint

RejectSearchSort refuses sortProperties on a chatMessage search.

Message hits come back in relevance order and nothing can change that. A caller building a chronological view from search results has to sort them itself, and finding that out here is cheaper than finding it out after the view exists.

func RejectSelectOnMessages added in v0.13.0

func RejectSelectOnMessages() Constraint

RejectSelectOnMessages refuses $select and $expand on a message listing.

Unlike the filter, these are genuinely refused, which is the distinction worth encoding: a caller may reasonably expect $select to trim a chat message and it returns 400 instead. The one exception is expanding replies on a channel message collection, which is supported and is the only way to read a thread in one request.

func RejectStaleETag added in v0.11.0

func RejectStaleETag(current string) Constraint

RejectStaleETag refuses a conditional write whose If-Match does not name the current version.

Exchange answers a stale mail tag with 400 and ErrorInvalidChangeKey, not the 412 the header implies, so the obvious precondition check misses it and the write looks like an ordinary bad request.

func RejectUnsupportedChannelMessageOptions added in v0.13.1

func RejectUnsupportedChannelMessageOptions() Constraint

RejectUnsupportedChannelMessageOptions keeps the channel collection and reply collection distinct from chat messages. Channel roots support $top and $expand=replies; replies support $top. Continuation links may also carry $skiptoken. Neither endpoint accepts the chat listing's $filter or $orderby.

func RejectUnsupportedFilterFunctions

func RejectUnsupportedFilterFunctions(extra ...string) Constraint

RejectUnsupportedFilterFunctions refuses filter functions Exchange does not implement. endswith is the notable one: it is valid OData and valid on other Graph resources, but on mail it answers ErrorInvalidUrlQueryFilter, so a "sender is at this domain" filter can never work.

func RejectUnsupportedMessageSortProperty added in v0.13.0

func RejectUnsupportedMessageSortProperty(sortable ...string) Constraint

RejectUnsupportedMessageSortProperty refuses an $orderby on anything but the two timestamps a message listing indexes.

func RequireAllDayAtMidnight added in v0.11.0

func RequireAllDayAtMidnight() Constraint

RequireAllDayAtMidnight refuses an all-day event whose ends are not midnight.

An all-day event is a pair of calendar dates rather than instants, and the service enforces that by requiring both ends at midnight. It reports the refusal without naming which end was wrong, and a client reading dates in a local zone produces exactly this shape without noticing.

func RequireAuthorization

func RequireAuthorization() Constraint

RequireAuthorization refuses a request without a bearer token, which is the single most embarrassing thing for a client to get wrong.

func RequireCalendarWindow added in v0.10.0

func RequireCalendarWindow() Constraint

RequireCalendarWindow refuses a calendar view that does not name the range it wants.

The service treats startDateTime and endDateTime as required parameters of the resource, not as an optional filter, and answers a request without them with ErrorInvalidArgument.

func RequireHeader

func RequireHeader(name, code, message string) Constraint

RequireHeader refuses a request that does not carry a header, for asserting that a client always sends one.

func RequireRuleSequence added in v0.11.0

func RequireRuleSequence() Constraint

RequireRuleSequence refuses a new inbox rule that does not say where it runs in the order.

The service requires a positive sequence and will not choose one. It answers a rule without it with a MessageRuleValidationError naming the field and not the remedy, so every rule created with a default-constructed body failed -- which is every rule, until something tried it against a real mailbox.

func RequireScopes added in v0.8.0

func RequireScopes(granted ...string) Constraint

RequireScopes refuses a request whose resource needs a permission the token was not granted, the way the service does.

This exists because of a bug that reached a real mailbox. A token is issued for the scopes a client *requests*, not for everything the user has consented to. Every command asked for the default mail scopes, so the mailbox settings commands were refused even though consent covered them -- and the error told the user to grant a permission they already held. A fake that answered every path identically could not have caught it: the whole bug lived in the difference between paths.

The refusal is deliberately as unhelpful as the real one. Graph answers a missing delegated permission with ErrorAccessDenied and names neither the permission nor the resource, so a caller that only works when the error is descriptive will not work in production either.

func RequireSearchEntityTypes added in v0.13.0

func RequireSearchEntityTypes(required ...string) Constraint

RequireSearchEntityTypes refuses a search body that does not name one of the entity types, so a mis-built request fails here instead of succeeding with an empty-looking result that reads as "nothing matched".

func RequireSortableFilter

func RequireSortableFilter(sortable ...string) Constraint

RequireSortableFilter refuses a request that both sorts and filters on a property outside the sortable set, the way Exchange answers InefficientFilter.

This is the constraint that broke most of the CLI's filters in production while every test passed: the default newest-first ordering meant almost any filter was paired with a sort.

func Teams added in v0.13.0

func Teams() []Constraint

Teams returns the constraints a real Teams tenant applies.

It is worth reading alongside ExchangeMail, because the two fail in opposite ways. Exchange refuses what it cannot serve, so the Exchange bundle is constraints: a bad request comes back as an error a test can see. Teams mostly answers anyway. An unservable filter is dropped, an oversized page is quietly trimmed, an enum the request did not opt into is replaced with a placeholder -- all with 200 OK and a body that parses.

That is why the Teams half of this fake lives mostly in TeamsShapers, and why using these constraints without those shapers reproduces the easy failures and none of the dangerous ones.

type Handler

type Handler func(*Request) Response

Handler answers a request.

type Option

type Option func(*Server)

Option configures a Server.

func WithConstraints

func WithConstraints(constraints ...Constraint) Option

WithConstraints makes the fake reject requests the real service would.

func WithShapers added in v0.12.0

func WithShapers(shapers ...Shaper) Option

WithShapers rewrites responses on their way out. Use it to reproduce how the service presents an answer, as distinct from whether it refuses one.

type Query

type Query struct {
	Select     []string
	Filter     string
	OrderBy    []string
	Search     string
	Top        int
	Skip       int
	Count      bool
	SkipToken  string
	DeltaToken string
	Raw        url.Values
}

Query is the parsed OData query string.

func (Query) Has

func (q Query) Has(name string) bool

Has reports whether a raw query parameter was sent.

type Recorded

type Recorded struct {
	Method string
	Path   string
	Query  Query
	Header http.Header
	Body   []byte
}

Recorded is one request the server received.

type Request

type Request struct {
	Method string
	// Path is the escaped request path.
	Path   string
	Query  Query
	Header http.Header
	Body   []byte
	// contains filtered or unexported fields
}

Request is what a handler is given.

func (*Request) EffectivePageSize

func (r *Request) EffectivePageSize(defaultSize, maxSize int) int

EffectivePageSize is the number of items a request should yield, applying the service's default and cap. Handlers use it to page realistically.

func (*Request) PageSize

func (r *Request) PageSize() (int, bool)

PageSize returns the odata.maxpagesize the caller asked for, and whether one was sent at all.

func (*Request) PathValue

func (r *Request) PathValue(name string) string

PathValue returns a wildcard captured by the route pattern, such as the id in "GET /me/messages/{id}".

func (*Request) Prefers

func (r *Request) Prefers(directive msgraph.PreferDirective) bool

Prefers reports whether the request carried a Prefer directive.

type Response

type Response struct {
	Status int
	Header http.Header
	// contains filtered or unexported fields
}

Response is what a handler returns.

func Collection

func Collection[T any](items []T, nextLink string) Response

Collection responds with a Graph collection page. A non-empty nextLink is echoed as @odata.nextLink; use Delta for a terminal delta page.

func Created

func Created[T any](value T) Response

Created responds 201 with a typed resource.

func Delta

func Delta[T any](items []T, deltaLink string) Response

Delta responds with a delta page carrying a deltaLink, marking the end of a change set.

func Empty

func Empty(status int) Response

Empty responds with a status and no body, for the 202 and 204 replies Graph gives to sends, moves, and deletes.

func Fault

func Fault(status int, code, message string) Response

Fault responds with a Graph error envelope.

func Item

func Item[T any](value T) Response

Item responds with a single typed resource.

func OutlookChunkAccepted added in v0.12.0

func OutlookChunkAccepted(receivedSoFar int64) Response

OutlookChunkAccepted is what an Outlook upload session answers for a chunk that is not the last one.

It is 200 with the ranges it still wants, not the 202 an upload session suggests. Reading the status as completion truncates the attachment at the first chunk, and a fake that answered 202 encoded that mistake so well the suite stayed green while real uploads lost data. The body decides, not the status.

func OutlookChunkComplete added in v0.12.0

func OutlookChunkComplete[T any](attachment T) Response

OutlookChunkComplete is what the session answers for the final chunk: 201 with the attachment it created.

func Raw added in v0.6.3

func Raw(status int, contentType string, body []byte) Response

Raw responds with an arbitrary body and content type, for the endpoints that do not speak JSON — a message's MIME representation, or an attachment's bytes.

func Throttled

func Throttled(retryAfterSeconds int) Response

Throttled responds 429 with a Retry-After header.

func (Response) WithHeader

func (r Response) WithHeader(name, value string) Response

WithHeader adds a response header.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a fake Graph endpoint.

func New

func New(tb testing.TB, opts ...Option) *Server

New starts a fake Graph endpoint and stops it when the test finishes.

func (*Server) Client

func (s *Server) Client(opts ...msgraph.Option) *msgraph.Client

Client returns a Graph client wired to this server with a static token.

func (*Server) Handle

func (s *Server) Handle(pattern string, handler Handler)

Handle registers a handler for a method-and-path pattern using the standard library's routing syntax, so "GET /me/messages/{id}" captures an id.

func (s *Server) Link(path string, query ...string) string

Link builds an absolute link back into this server, for a nextLink or a deltaLink. The Graph client refuses to follow a link to another host, so a test must not invent one.

func (*Server) Requests

func (s *Server) Requests() []Recorded

Requests returns every request received so far, oldest first.

func (*Server) Reset

func (s *Server) Reset()

Reset discards recorded requests, for a test that runs several commands.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) URL

func (s *Server) URL() string

URL is the base URL to point a client at.

type Shaper added in v0.12.0

type Shaper func(*Request, *Response)

A Shaper rewrites a response on its way out, so the fake can reproduce how the service presents an answer rather than only whether it gives one.

Constraints cover refusals. This covers the other half: a service that answers successfully but in a shape a client does not expect. Graph naming zones with Windows identifiers is the example -- nothing is refused, and a client that assumes IANA names silently computes the wrong instant.

func DropSenderOnSystemEvents added in v0.13.0

func DropSenderOnSystemEvents() Shaper

DropSenderOnSystemEvents removes from wherever eventDetail is present.

Nothing sent a system event message: the service generated it, and from is null. A fake that helpfully supplies a sender lets a client dereference it unconditionally and pass, then panic or render a blank name against a real chat on the first membership change.

func DropTopicOnOneOnOneChats added in v0.13.0

func DropTopicOnOneOnOneChats() Shaper

DropTopicOnOneOnOneChats removes topic from every one-on-one chat.

The service sends null, because a one-on-one chat has no name of its own -- its name is the other participant, which the caller has to assemble from the members. A fake that supplies a topic renders a tidy chat list in tests and a column of blank rows in production, where most chats are one-on-one.

func HideEnumsWithoutPrefer added in v0.13.0

func HideEnumsWithoutPrefer() Shaper

HideEnumsWithoutPrefer replaces every messageType outside the base set with unknownFutureValue unless the request asked to see evolvable enum members.

This is the most valuable shaper in the bundle. messageType is an evolvable enum, so a request that does not send Prefer: include-unknown-enum-members gets systemEventMessage reported as unknownFutureValue -- with no error, and with eventDetail still populated. In a real chat, member joins, renames and call notices are a large minority of the history, so a client switching on the type renders a substantial part of every conversation as nothing at all.

It is also the only check that proves the header survives the network. A client can set the directive perfectly and have a proxy strip it; nothing else in a test suite would notice.

func NameZonesTheWindowsWay added in v0.12.0

func NameZonesTheWindowsWay(zone string) Shaper

NameZonesTheWindowsWay rewrites every timeZone in a response to a Windows identifier, the way Graph does once a request asks for a zone.

This is a shaper rather than a constraint because nothing is refused. The response is perfectly valid and the client still gets it wrong, which is the harder failure to find: a calendar that renders confidently and is hours or a day out. Rendering an all-day event this way showed every holiday on the wrong date.

func PageExpandedReplies added in v0.13.0

func PageExpandedReplies(limit int) Shaper

PageExpandedReplies cuts an expanded replies array to the cap and injects the per-message continuation link the service sends.

This is a second pagination nested inside the first. The collection's own @odata.nextLink pages root messages and says nothing about replies, so a client that follows only the outer link -- which is every client written against every other Graph collection -- truncates each long thread and displays a conversation that stops mid-argument, with no error and no gap.

func PopulateOnlyJoinedTeamsFields added in v0.13.0

func PopulateOnlyJoinedTeamsFields() Shaper

PopulateOnlyJoinedTeamsFields nulls the team properties that listing joined teams does not fill in.

The response carries the whole team shape, so it looks complete. It is not: webUrl, visibility, internalId and the settings all come back null, and only a Get on the individual team populates them. A client reading visibility off a listing sees an empty string and concludes the team is public, which is a different claim from "not loaded".

func RootChannelMessagesOnly added in v0.13.0

func RootChannelMessagesOnly() Shaper

RootChannelMessagesOnly drops replies from a channel message collection.

A channel listing returns root messages and nothing else, however deep the paging goes. A transcript built from it alone shows every conversation opener and none of the conversation, so a fake that mixes replies into the collection hides the need to expand them or fetch them per message.

func StripHeader added in v0.12.0

func StripHeader(name string) Shaper

StripHeader removes a response header the real service does not send.

Mail is the case worth reproducing: there is no ETag header on a message, the version is the @odata.etag body property, and a client reading the header finds nothing and silently turns every conditional write into an unconditional one.

func TeamsShapers added in v0.13.0

func TeamsShapers() []Shaper

TeamsShapers returns the shapers that present a Teams answer the way the service presents it.

These matter more than the constraints. Everything here answers 200 with a body that parses, and every one of them has a client-side failure that no amount of error handling catches: a third of a chat rendered as blank lines, a member list that stops at twenty-five without saying so, a thread that ends mid-argument. A fake that returns the convenient shape agrees with the client and proves nothing.

func TruncateExpandedMembers added in v0.13.0

func TruncateExpandedMembers(limit int) Shaper

TruncateExpandedMembers cuts an expanded members array to the cap and emits no continuation link.

The absent link is the point. Everywhere else in Graph a truncated collection carries a nextLink, so a client that follows links everywhere is correct everywhere -- except here, where it silently reports a two hundred person chat as having twenty-five members and no indication otherwise.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL