Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions src/m365/spp/commands/contentcenter/contentcenter-list.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import assert from 'assert';
import sinon from 'sinon';
import auth from '../../../../Auth.js';
import { CommandInfo } from '../../../../cli/CommandInfo.js';
import { cli } from '../../../../cli/cli.js';
import { Logger } from '../../../../cli/Logger.js';
import { CommandError } from '../../../../Command.js';
import config from '../../../../config.js';
Expand All @@ -11,12 +13,14 @@ import { session } from '../../../../utils/session.js';
import { sinonUtil } from '../../../../utils/sinonUtil.js';
import { spo } from '../../../../utils/spo.js';
import commands from '../../commands.js';
import command from './contentcenter-list.js';
import command, { options } from './contentcenter-list.js';

describe(commands.CONTENTCENTER_LIST, () => {
let log: string[];
let logger: Logger;
let loggerLogSpy: sinon.SinonSpy;
let commandInfo: CommandInfo;
let commandOptionsSchema: typeof options;

before(() => {
sinon.stub(auth, 'restoreAuth').resolves();
Expand All @@ -27,6 +31,8 @@ describe(commands.CONTENTCENTER_LIST, () => {
sinon.stub(spo, 'ensureFormDigest').resolves({ FormDigestValue: 'abc', FormDigestTimeoutSeconds: 1800, FormDigestExpiresAt: new Date(), WebFullUrl: 'https://contoso.sharepoint.com' });
auth.connection.active = true;
auth.connection.spoUrl = 'https://contoso.sharepoint.com';
commandInfo = cli.getCommandInfo(command);
commandOptionsSchema = commandInfo.command.getSchemaToParse() as typeof options;
});

beforeEach(() => {
Expand Down Expand Up @@ -69,6 +75,16 @@ describe(commands.CONTENTCENTER_LIST, () => {
assert.deepStrictEqual(command.defaultProperties(), ['Title', 'Url']);
});

it('passes validation with no options', () => {
const actual = commandOptionsSchema.safeParse({});
assert.strictEqual(actual.success, true);
});

it('fails validation with unknown options', () => {
const actual = commandOptionsSchema.safeParse({ unknownOption: 'value' });
assert.strictEqual(actual.success, false);
});

it('retrieves list of content centers', async () => {
sinon.stub(request, 'post').callsFake(async (opts) => {
if ((opts.url === `https://contoso-admin.sharepoint.com/_vti_bin/client.svc/ProcessQuery`)) {
Expand Down Expand Up @@ -99,7 +115,7 @@ describe(commands.CONTENTCENTER_LIST, () => {
throw 'Invalid request';
});

await command.action(logger, { options: {} });
await command.action(logger, { options: commandOptionsSchema.parse({}) });
assert(loggerLogSpy.calledOnceWithExactly([
{
"_ObjectType_": "Microsoft.Online.SharePoint.TenantAdministration.SiteProperties", "_ObjectIdentity_": "487c379e-80f8-4000-80be-1d37a4995717|908bed80-a04a-4433-b4a0-883d9847d110:67753f63-bc14-4012-869e-f808a43fe023\nSiteProperties\nhttps%3a%2f%2fcontoso.sharepoint.com%2fsites%2fctest_101", "AllowDownloadingNonWebViewableFiles": false, "AllowEditing": false, "AllowSelfServiceUpgrade": true, "AverageResourceUsage": 0, "CommentsOnSitePagesDisabled": false, "CompatibilityLevel": 15, "ConditionalAccessPolicy": 0, "CurrentResourceUsage": 0, "DenyAddAndCustomizePages": 2, "DisableAppViews": 0, "DisableCompanyWideSharingLinks": 0, "DisableFlows": 0, "HasHolds": false, "LastContentModifiedDate": "/Date(2017,11,17,4,12,28,997)/", "Lcid": 1033, "LockIssue": null, "LockState": "Unlock", "NewUrl": "", "Owner": "", "OwnerEmail": null, "PWAEnabled": 0, "RestrictedToRegion": 3, "SandboxedCodeActivationCapability": 0, "SharingAllowedDomainList": null, "SharingBlockedDomainList": null, "SharingCapability": 1, "SharingDomainRestrictionMode": 0, "ShowPeoplePickerSuggestionsForGuestUsers": false, "SiteDefinedSharingCapability": 0, "Status": "Active", "StorageMaximumLevel": 26214400, "StorageQuotaType": null, "StorageUsage": 1, "StorageWarningLevel": 25574400, "Template": "CONTENTCTR#0", "TimeZoneId": 13, "Title": "Content Center 101", "Url": "https:\u002f\u002fcontoso.sharepoint.com\u002fsites\u002fctest_101", "UserCodeMaximumLevel": 300, "UserCodeWarningLevel": 200, "WebsCount": 0
Expand Down Expand Up @@ -160,7 +176,7 @@ describe(commands.CONTENTCENTER_LIST, () => {
throw 'Invalid request';
});

await command.action(logger, { options: {} });
await command.action(logger, { options: commandOptionsSchema.parse({}) });
assert(loggerLogSpy.calledOnceWith([
{
"_ObjectType_": "Microsoft.Online.SharePoint.TenantAdministration.SiteProperties", "_ObjectIdentity_": "487c379e-80f8-4000-80be-1d37a4995717|908bed80-a04a-4433-b4a0-883d9847d110:67753f63-bc14-4012-869e-f808a43fe023\nSiteProperties\nhttps%3a%2f%2fcontoso.sharepoint.com%2fsites%2fctest_101", "AllowDownloadingNonWebViewableFiles": false, "AllowEditing": false, "AllowSelfServiceUpgrade": true, "AverageResourceUsage": 0, "CommentsOnSitePagesDisabled": false, "CompatibilityLevel": 15, "ConditionalAccessPolicy": 0, "CurrentResourceUsage": 0, "DenyAddAndCustomizePages": 2, "DisableAppViews": 0, "DisableCompanyWideSharingLinks": 0, "DisableFlows": 0, "HasHolds": false, "LastContentModifiedDate": "/Date(2017,11,17,4,12,28,997)/", "Lcid": 1033, "LockIssue": null, "LockState": "Unlock", "NewUrl": "", "Owner": "", "OwnerEmail": null, "PWAEnabled": 0, "RestrictedToRegion": 3, "SandboxedCodeActivationCapability": 0, "SharingAllowedDomainList": null, "SharingBlockedDomainList": null, "SharingCapability": 1, "SharingDomainRestrictionMode": 0, "ShowPeoplePickerSuggestionsForGuestUsers": false, "SiteDefinedSharingCapability": 0, "Status": "Active", "StorageMaximumLevel": 26214400, "StorageQuotaType": null, "StorageUsage": 1, "StorageWarningLevel": 25574400, "Template": "CONTENTCTR#0", "TimeZoneId": 13, "Title": "Content Center 101", "Url": "https:\u002f\u002fcontoso.sharepoint.com\u002fsites\u002fctest_101", "UserCodeMaximumLevel": 300, "UserCodeWarningLevel": 200, "WebsCount": 0
Expand Down Expand Up @@ -193,12 +209,12 @@ describe(commands.CONTENTCENTER_LIST, () => {
throw 'Invalid request';
});

await assert.rejects(command.action(logger, { options: { debug: true } } as any), new CommandError("Syntax error in the filter expression 'Url like 'test''."));
await assert.rejects(command.action(logger, { options: commandOptionsSchema.parse({ debug: true }) }), new CommandError("Syntax error in the filter expression 'Url like 'test''."));
});

it('correctly handles random API error', async () => {
sinon.stub(request, 'post').rejects(new Error('An error has occurred'));

await assert.rejects(command.action(logger, { options: { debug: true } } as any), new CommandError('An error has occurred'));
await assert.rejects(command.action(logger, { options: commandOptionsSchema.parse({ debug: true }) }), new CommandError('An error has occurred'));
});
});
8 changes: 8 additions & 0 deletions src/m365/spp/commands/contentcenter/contentcenter-list.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import { Logger } from '../../../../cli/Logger.js';
import config from '../../../../config.js';
import request, { CliRequestOptions } from '../../../../request.js';
Expand All @@ -7,6 +9,8 @@ import { SiteProperties } from '../../../spo/commands/site/SiteProperties.js';
import { SPOSitePropertiesEnumerable } from '../../../spo/commands/site/SPOSitePropertiesEnumerable.js';
import commands from '../../commands.js';

export const options = globalOptionsZod.strict();

class SppContentCenterListCommand extends SpoCommand {
public get name(): string {
return commands.CONTENTCENTER_LIST;
Expand All @@ -20,6 +24,10 @@ class SppContentCenterListCommand extends SpoCommand {
return ['Title', 'Url'];
}

public get schema(): z.ZodType | undefined {
return options;
}

public async commandAction(logger: Logger): Promise<void> {
try {
if (this.verbose) {
Expand Down
65 changes: 38 additions & 27 deletions src/m365/spp/commands/model/model-get.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import { pid } from '../../../../utils/pid.js';
import { session } from '../../../../utils/session.js';
import { sinonUtil } from '../../../../utils/sinonUtil.js';
import commands from '../../commands.js';
import command from './model-get.js';
import command, { options } from './model-get.js';
import { spp } from '../../../../utils/spp.js';

describe(commands.MODEL_GET, () => {
let log: string[];
let logger: Logger;
let loggerLogSpy: sinon.SinonSpy;
let commandInfo: CommandInfo;
let commandOptionsSchema: typeof options;
const model = {
"AIBuilderHybridModelType": null,
"AzureCognitivePrebuiltModelName": null,
Expand Down Expand Up @@ -175,6 +176,7 @@ describe(commands.MODEL_GET, () => {
sinon.stub(spp, 'assertSiteIsContentCenter').resolves();
auth.connection.active = true;
commandInfo = cli.getCommandInfo(command);
commandOptionsSchema = commandInfo.command.getSchemaToParse() as typeof options;
});

beforeEach(() => {
Expand Down Expand Up @@ -214,34 +216,43 @@ describe(commands.MODEL_GET, () => {
assert.notStrictEqual(command.description, null);
});

it('passes validation when required parameters are valid with id', async () => {
const actual = await command.validate({ options: { siteUrl: 'https://contoso.sharepoint.com/sites/sales', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' } }, commandInfo);
assert.strictEqual(actual, true);
it('passes validation when required parameters are valid with id', () => {
const actual = commandOptionsSchema.safeParse({ siteUrl: 'https://contoso.sharepoint.com/sites/sales', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' });
assert.strictEqual(actual.success, true);
});

it('passes validation when required parameters are valid with title', async () => {
const actual = await command.validate({ options: { siteUrl: 'https://contoso.sharepoint.com/sites/sales', title: 'ModelName' } }, commandInfo);
assert.strictEqual(actual, true);
it('passes validation when required parameters are valid with title', () => {
const actual = commandOptionsSchema.safeParse({ siteUrl: 'https://contoso.sharepoint.com/sites/sales', title: 'ModelName' });
assert.strictEqual(actual.success, true);
});

it('passes validation when required parameters are valid with id and withPublications', async () => {
const actual = await command.validate({ options: { siteUrl: 'https://contoso.sharepoint.com/sites/sales', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f', withPublications: true } }, commandInfo);
assert.strictEqual(actual, true);
it('passes validation when required parameters are valid with id and withPublications', () => {
const actual = commandOptionsSchema.safeParse({ siteUrl: 'https://contoso.sharepoint.com/sites/sales', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f', withPublications: true });
assert.strictEqual(actual.success, true);
});

it('passes validation when required parameters are valid with title and withPublications', async () => {
const actual = await command.validate({ options: { siteUrl: 'https://contoso.sharepoint.com/sites/sales', title: 'ModelName', withPublications: true } }, commandInfo);
assert.strictEqual(actual, true);
it('passes validation when required parameters are valid with title and withPublications', () => {
const actual = commandOptionsSchema.safeParse({ siteUrl: 'https://contoso.sharepoint.com/sites/sales', title: 'ModelName', withPublications: true });
assert.strictEqual(actual.success, true);
});

it('fails validation when siteUrl is not valid', async () => {
const actual = await command.validate({ options: { siteUrl: 'invalidUrl', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' } }, commandInfo);
assert.notStrictEqual(actual, true);
it('fails validation when siteUrl is not valid', () => {
const actual = commandOptionsSchema.safeParse({ siteUrl: 'invalidUrl', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' });
assert.strictEqual(actual.success, false);
});

it('fails validation when id is not valid', async () => {
const actual = await command.validate({ options: { siteUrl: 'https://contoso.sharepoint.com/sites/sales', id: 'foo' } }, commandInfo);
assert.notStrictEqual(actual, true);
it('fails validation when id is not valid', () => {
const actual = commandOptionsSchema.safeParse({ siteUrl: 'https://contoso.sharepoint.com/sites/sales', id: 'foo' });
assert.strictEqual(actual.success, false);
});

it('fails validation with unknown options', () => {
const actual = commandOptionsSchema.safeParse({
siteUrl: 'https://contoso.sharepoint.com/sites/sales',
id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f',
unknownOption: 'value'
});
assert.strictEqual(actual.success, false);
});

it('correctly handles a model is not found error by id', async () => {
Expand All @@ -257,42 +268,42 @@ describe(commands.MODEL_GET, () => {
}
});

await assert.rejects(command.action(logger, { options: { verbose: true, siteUrl: 'https://contoso.sharepoint.com/sites/portal', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' } }),
await assert.rejects(command.action(logger, { options: commandOptionsSchema.parse({ verbose: true, siteUrl: 'https://contoso.sharepoint.com/sites/portal', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' }) }),
new CommandError('File Not Found.'));
});

it('retrieves model by id', async () => {
sinon.stub(spp, 'getModelById').resolves(model);

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], modelResult);
});

it('retrieves model by title', async () => {
sinon.stub(spp, 'getModelByTitle').resolves(model);

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName' } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName' }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], modelResult);
});

it('retrieves model without additional information by title', async () => {
sinon.stub(spp, 'getModelByTitle').resolves(modelWithoutAdditionalData as any);

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName' } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName' }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], modelResultWithoutAdditionalData);
});

it('retrieves model by title with classifier suffix', async () => {
sinon.stub(spp, 'getModelByTitle').resolves(model);

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName.classifier' } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName.classifier' }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], modelResult);
});

it('gets correct model when the site URL has a trailing slash', async () => {
sinon.stub(spp, 'getModelById').resolves(model);

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal/', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal/', id: '9b1b1e42-794b-4c71-93ac-5ed92488b67f' }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], modelResult);
});

Expand All @@ -306,7 +317,7 @@ describe(commands.MODEL_GET, () => {
throw 'Invalid request';
});

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal', id: '164720c8-35ee-4157-ba26-db6726264f9d', withPublications: true, verbose: true } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal', id: '164720c8-35ee-4157-ba26-db6726264f9d', withPublications: true, verbose: true }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], { ...modelResult, Publications: publications });
});

Expand All @@ -320,7 +331,7 @@ describe(commands.MODEL_GET, () => {
throw 'Invalid request';
});

await command.action(logger, { options: { siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName', withPublications: true } });
await command.action(logger, { options: commandOptionsSchema.parse({ siteUrl: 'https://contoso.sharepoint.com/sites/portal', title: 'ModelName', withPublications: true }) });
assert.deepStrictEqual(loggerLogSpy.lastCall.args[0], { ...modelResult, Publications: publications });
});
});
92 changes: 31 additions & 61 deletions src/m365/spp/commands/model/model-get.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import { Logger } from '../../../../cli/Logger.js';
import GlobalOptions from '../../../../GlobalOptions.js';
import { odata } from '../../../../utils/odata.js';
import { spp } from '../../../../utils/spp.js';
import { urlUtil } from '../../../../utils/urlUtil.js';
import { validation } from '../../../../utils/validation.js';
import SpoCommand from '../../../base/SpoCommand.js';
import commands from '../../commands.js';

export const options = z.strictObject({
...globalOptionsZod.shape,
siteUrl: z.string()
.refine(url => validation.isValidSharePointUrl(url) === true, {
error: e => `'${e.input}' is not a valid SharePoint Online site URL.`
})
.alias('u'),
id: z.string()
.refine(val => validation.isValidGuid(val), {
message: `The value specified for option 'id' is not a valid GUID.`
})
.optional()
.alias('i'),
title: z.string().optional().alias('t'),
withPublications: z.boolean().optional()
});

declare type Options = z.infer<typeof options>;

interface CommandArgs {
options: Options;
}

interface Options extends GlobalOptions {
siteUrl: string;
id?: string;
title?: string;
withPublications?: boolean;
}

class SppModelGetCommand extends SpoCommand {
public get name(): string {
return commands.MODEL_GET;
Expand All @@ -27,62 +40,19 @@ class SppModelGetCommand extends SpoCommand {
return 'Retrieves information about a document understanding model';
}

constructor() {
super();

this.#initTelemetry();
this.#initOptions();
this.#initValidators();
this.#initOptionSets();
this.#initTypes();
public get schema(): z.ZodType | undefined {
return options;
}

#initTelemetry(): void {
this.telemetry.push((args: CommandArgs) => {
Object.assign(this.telemetryProperties, {
id: typeof args.options.id !== 'undefined',
title: typeof args.options.title !== 'undefined',
withPublications: !!args.options.withPublications
});
});
}

#initOptions(): void {
this.options.unshift(
{
option: '-u, --siteUrl <siteUrl>'
},
{
option: '-i, --id [id]'
},
{
option: '-t, --title [title]'
},
{
option: '--withPublications'
}
);
}

#initValidators(): void {
this.validators.push(
async (args: CommandArgs) => {
if (args.options.id && !validation.isValidGuid(args.options.id)) {
return `${args.options.id} is not a valid GUID for option 'id'.`;
public getRefinedSchema(schema: typeof options): z.ZodObject<any> | undefined {
return schema
.refine(opts => [opts.id, opts.title].filter(x => x !== undefined).length === 1, {
message: `Specify either 'id' or 'title', but not both.`,
params: {
customCode: 'optionSet',
options: ['id', 'title']
}

return validation.isValidSharePointUrl(args.options.siteUrl);
}
);
}

#initOptionSets(): void {
this.optionSets.push({ options: ['id', 'title'] });
}

#initTypes(): void {
this.types.string.push('siteUrl', 'id', 'title');
this.types.boolean.push('withPublications');
});
}

public async commandAction(logger: Logger, args: CommandArgs): Promise<void> {
Expand Down
Loading
Loading