Allow multiple URL segments per document (#18603)

* Code tidy - XML header comments, method ordering, warning resolution.

* Add extension method for retrieving all URL segments for a document.

* Cache and persist multiple URL segments per document.

* Allowed segment providers to terminate or allow additional segments.
Set up currently failing integration test for expected routes.

* Resolved cache issue to ensure passing new integration tests.

* Fixed failing integration test.

* Test class naming tidy up.

* Added resolution and persistance of a primary segment, to retain previous behaviour when a single segment is retrieved.

* Further integration tests.

* Resolved backward compatibility of interface.

* Supress amends made to integration tests.

* Aligned naming of integration tests.

* Removed unused using, added XML header comment.

* Throw on missing table in migration.

* Code clean-up.

* Fix multiple enumeration

* Used default on migrated column.

* Use 1 over true for default value.

* Remove unused logger

---------

Co-authored-by: mole <nikolajlauridsen@protonmail.ch>
This commit is contained in:
Andy Butland
2025-03-13 13:47:46 +01:00
committed by GitHub
parent da5669d9fc
commit e9c97f8c9b
13 changed files with 901 additions and 481 deletions

View File

@@ -11,7 +11,7 @@ public static class ContentBaseExtensions
private static DefaultUrlSegmentProvider? _defaultUrlSegmentProvider;
/// <summary>
/// Gets the URL segment for a specified content and culture.
/// Gets a single URL segment for a specified content and culture.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="shortStringHelper"></param>
@@ -19,29 +19,73 @@ public static class ContentBaseExtensions
/// <param name="culture">The culture.</param>
/// <param name="published">Whether to get the published or draft.</param>
/// <returns>The URL segment.</returns>
/// <remarks>
/// If more than one URL segment provider is available, the first one that returns a non-null value will be returned.
/// </remarks>
public static string? GetUrlSegment(this IContentBase content, IShortStringHelper shortStringHelper, IEnumerable<IUrlSegmentProvider> urlSegmentProviders, string? culture = null, bool published = true)
{
if (content == null)
{
throw new ArgumentNullException(nameof(content));
}
var urlSegment = GetUrlSegments(content, urlSegmentProviders, culture, published).FirstOrDefault();
if (urlSegmentProviders == null)
{
throw new ArgumentNullException(nameof(urlSegmentProviders));
}
// Ensure we have at least the segment from the default URL provider returned.
urlSegment ??= GetDefaultUrlSegment(shortStringHelper, content, culture, published);
var url = urlSegmentProviders.Select(p => p.GetUrlSegment(content, published, culture)).FirstOrDefault(u => u != null);
if (url == null)
return urlSegment;
}
/// <summary>
/// Gets all URL segments for a specified content and culture.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="shortStringHelper"></param>
/// <param name="urlSegmentProviders"></param>
/// <param name="culture">The culture.</param>
/// <param name="published">Whether to get the published or draft.</param>
/// <returns>The collection of URL segments.</returns>
public static IEnumerable<string> GetUrlSegments(this IContentBase content, IShortStringHelper shortStringHelper, IEnumerable<IUrlSegmentProvider> urlSegmentProviders, string? culture = null, bool published = true)
{
var urlSegments = GetUrlSegments(content, urlSegmentProviders, culture, published).Distinct().ToList();
// Ensure we have at least the segment from the default URL provider returned.
if (urlSegments.Count == 0)
{
if (_defaultUrlSegmentProvider == null)
var defaultUrlSegment = GetDefaultUrlSegment(shortStringHelper, content, culture, published);
if (defaultUrlSegment is not null)
{
_defaultUrlSegmentProvider = new DefaultUrlSegmentProvider(shortStringHelper);
urlSegments.Add(defaultUrlSegment);
}
url = _defaultUrlSegmentProvider.GetUrlSegment(content, culture); // be safe
}
return url;
return urlSegments;
}
private static IEnumerable<string> GetUrlSegments(
IContentBase content,
IEnumerable<IUrlSegmentProvider> urlSegmentProviders,
string? culture,
bool published)
{
foreach (IUrlSegmentProvider urlSegmentProvider in urlSegmentProviders)
{
var segment = urlSegmentProvider.GetUrlSegment(content, published, culture);
if (string.IsNullOrEmpty(segment) == false)
{
yield return segment;
if (urlSegmentProvider.AllowAdditionalSegments is false)
{
yield break;
}
}
}
}
private static string? GetDefaultUrlSegment(
IShortStringHelper shortStringHelper,
IContentBase content,
string? culture,
bool published)
{
_defaultUrlSegmentProvider ??= new DefaultUrlSegmentProvider(shortStringHelper);
return _defaultUrlSegmentProvider.GetUrlSegment(content, published, culture);
}
}

View File

@@ -1,9 +1,32 @@
namespace Umbraco.Cms.Core.Models;
/// <summary>
/// Represents a URL segment for a published document.
/// </summary>
public class PublishedDocumentUrlSegment
{
/// <summary>
/// Gets or sets the document key.
/// </summary>
public required Guid DocumentKey { get; set; }
/// <summary>
/// Gets or sets the language Id.
/// </summary>
public required int LanguageId { get; set; }
/// <summary>
/// Gets or sets the URL segment string.
/// </summary>
public required string UrlSegment { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the URL segment is for a draft.
/// </summary>
public required bool IsDraft { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the URL segment is the primary one (first resolved from the collection of URL providers).
/// </summary>
public required bool IsPrimary { get; set; }
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,38 +1,97 @@
using Umbraco.Cms.Core.Media.EmbedProviders;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Routing;
namespace Umbraco.Cms.Core.Services;
/// <summary>
/// Defines operations for handling document URLs.
/// </summary>
public interface IDocumentUrlService
{
/// <summary>
/// Initializes the service and ensure the content in the database is correct with the current configuration.
/// </summary>
/// <param name="forceEmpty"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <param name="forceEmpty">Forces an early return when we know there are no routes (i.e. on install).</param>
/// <param name="cancellationToken">The cancellation token.</param>
Task InitAsync(bool forceEmpty, CancellationToken cancellationToken);
Task RebuildAllUrlsAsync();
/// <summary>
/// Gets the Url from a document key, culture and segment. Preview urls are returned if isPreview is true.
/// Rebuilds all document URLs.
/// </summary>
Task RebuildAllUrlsAsync();
/// <summary>
/// Gets a single URL segment from a document key and culture. Preview urls are returned if isDraft is true.
/// </summary>
/// <param name="documentKey">The key of the document.</param>
/// <param name="culture">The culture code.</param>
/// <param name="isDraft">Whether to get the url of the draft or published document.</param>
/// <returns>The url of the document.</returns>
/// <returns>A URL segment for the document.</returns>
/// <remarks>If more than one segment is available, the first retrieved and indicated as primary will be returned.</remarks>
string? GetUrlSegment(Guid documentKey, string culture, bool isDraft);
/// <summary>
/// Gets the URL segments from a document key and culture. Preview urls are returned if isDraft is true.
/// </summary>
/// <param name="documentKey">The key of the document.</param>
/// <param name="culture">The culture code.</param>
/// <param name="isDraft">Whether to get the url of the draft or published document.</param>
/// <returns>The URL segments for the document.</returns>
IEnumerable<string> GetUrlSegments(Guid documentKey, string culture, bool isDraft)
=> throw new NotImplementedException();
/// <summary>
/// Creates or updates the URL segments for a single document.
/// </summary>
/// <param name="key">The document key.</param>
Task CreateOrUpdateUrlSegmentsAsync(Guid key);
/// <summary>
/// Creates or updates the URL segments for a document and it's descendants.
/// </summary>
/// <param name="key">The document key.</param>
Task CreateOrUpdateUrlSegmentsWithDescendantsAsync(Guid key);
/// <summary>
/// Creates or updates the URL segments for a collection of documents.
/// </summary>
/// <param name="documents">The document collection.</param>
Task CreateOrUpdateUrlSegmentsAsync(IEnumerable<IContent> documents);
/// <summary>
/// Deletes all URLs from the cache for a collection of document keys.
/// </summary>
/// <param name="documentKeys">The collection of document keys.</param>
Task DeleteUrlsFromCacheAsync(IEnumerable<Guid> documentKeys);
/// <summary>
/// Gets a document key by route.
/// </summary>
/// <param name="route">The route.</param>
/// <param name="culture">The culture code.</param>
/// <param name="documentStartNodeId">The document start node Id.</param>
/// <param name="isDraft">Whether to get the url of the draft or published document.</param>
/// <returns>The document key, or null if not found.</returns>
Guid? GetDocumentKeyByRoute(string route, string? culture, int? documentStartNodeId, bool isDraft);
/// <summary>
/// Gets all the URLs for a given content key.
/// </summary>
/// <param name="contentKey">The content key.</param>
[Obsolete("This method is obsolete and will be removed in future versions. Use IPublishedUrlInfoProvider.GetAllAsync instead. Scheduled for removal in Umbraco 17.")]
Task<IEnumerable<UrlInfo>> ListUrlsAsync(Guid contentKey);
Task CreateOrUpdateUrlSegmentsWithDescendantsAsync(Guid key);
Task CreateOrUpdateUrlSegmentsAsync(Guid key);
/// <summary>
/// Gets the legacy route format for a document key and culture.
/// </summary>
/// <param name="key">The key of the document.</param>
/// <param name="culture">The culture code.</param>
/// <param name="isDraft">Whether to get the url of the draft or published document.</param>
/// <returns></returns>
string GetLegacyRouteFormat(Guid key, string? culture, bool isDraft);
/// <summary>
/// Gets a value indicating whether any URLs have been cached.
/// </summary>
bool HasAny();
}

View File

@@ -8,6 +8,16 @@ namespace Umbraco.Cms.Core.Strings;
/// <remarks>Url segments should comply with IETF RFCs regarding content, encoding, etc.</remarks>
public interface IUrlSegmentProvider
{
/// <summary>
/// Gets a value indicating whether the URL segment provider allows additional segments after providing one.
/// </summary>
/// <remarks>
/// If set to true, when more than one URL segment provider is available, futher providers after this one in the collection will be called
/// even if the current provider provides a segment.
/// If false, the provider will terminate the chain of URL segment providers if it provides a segment.
/// </remarks>
bool AllowAdditionalSegments => false;
/// <summary>
/// Gets the URL segment for a specified content and culture.
/// </summary>
@@ -20,6 +30,18 @@ public interface IUrlSegmentProvider
/// URL per culture.
/// </remarks>
string? GetUrlSegment(IContentBase content, string? culture = null);
/// <summary>
/// Gets the URL segment for a specified content, published status and and culture.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="culture">The culture.</param>
/// <returns>The URL segment.</returns>
/// <remarks>
/// This is for when Umbraco is capable of managing more than one URL
/// per content, in 1-to-1 multilingual configurations. Then there would be one
/// URL per culture.
/// </remarks>
string? GetUrlSegment(IContentBase content, bool published, string? culture = null) => GetUrlSegment(content, culture);
// TODO: For the 301 tracking, we need to add another extended interface to this so that

View File

@@ -111,5 +111,8 @@ public class UmbracoPlan : MigrationPlan
// To 15.3.0
To<V_15_3_0.AddNameAndDescriptionToWebhooks>("{7B11F01E-EE33-4B0B-81A1-F78F834CA45B}");
// To 15.4.0
To<V_15_4_0.UpdateDocumentUrlToPersistMultipleSegmentsPerDocument>("{A9E72794-4036-4563-B543-1717C73B8879}");
}
}

View File

@@ -28,7 +28,7 @@ public class AddNameAndDescriptionToWebhooks : MigrationBase
}
else
{
Logger.LogWarning($"Table {Constants.DatabaseSchema.Tables.Webhook} does not exist so the addition of the name and description by columnss in migration {nameof(AddNameAndDescriptionToWebhooks)} cannot be completed.");
Logger.LogWarning($"Table {Constants.DatabaseSchema.Tables.Webhook} does not exist so the addition of the name and description by columns in migration {nameof(AddNameAndDescriptionToWebhooks)} cannot be completed.");
}
}

View File

@@ -0,0 +1,63 @@
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_15_4_0;
/// <summary>
/// Migration to make necessary schema updates to support multiple segments per document.
/// </summary>
public class UpdateDocumentUrlToPersistMultipleSegmentsPerDocument : MigrationBase
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateDocumentUrlToPersistMultipleSegmentsPerDocument"/> class.
/// </summary>
public UpdateDocumentUrlToPersistMultipleSegmentsPerDocument(IMigrationContext context)
: base(context)
{
}
/// <inheritdoc/>
protected override void Migrate()
{
Logger.LogDebug("Schema updates to {TableName} for support of multiple segments per document", Constants.DatabaseSchema.Tables.DocumentUrl);
if (TableExists(Constants.DatabaseSchema.Tables.DocumentUrl))
{
ExtendUniqueIndexAcrossSegmentField();
AddAndPopulateIsPrimaryColumn();
}
else
{
throw new InvalidOperationException(
$"Table {Constants.DatabaseSchema.Tables.DocumentUrl} does not exist so the migration {nameof(UpdateDocumentUrlToPersistMultipleSegmentsPerDocument)} could not be completed.");
}
}
private void ExtendUniqueIndexAcrossSegmentField()
{
Logger.LogDebug("Extending the unique index on {TableName} to include the urlSegment column", Constants.DatabaseSchema.Tables.DocumentUrl);
var indexName = "IX_" + Constants.DatabaseSchema.Tables.DocumentUrl;
if (IndexExists(indexName))
{
DeleteIndex<DocumentUrlDto>(indexName);
}
CreateIndex<DocumentUrlDto>(indexName);
}
private void AddAndPopulateIsPrimaryColumn()
{
const string IsPrimaryColumnName = "isPrimary";
Logger.LogDebug("Adding the {Column} column {TableName} to include the urlSegment column", IsPrimaryColumnName, Constants.DatabaseSchema.Tables.DocumentUrl);
var columns = Context.SqlContext.SqlSyntax.GetColumnsInSchema(Context.Database).ToList();
if (columns
.SingleOrDefault(x => x.TableName == Constants.DatabaseSchema.Tables.DocumentUrl && x.ColumnName == IsPrimaryColumnName) is null)
{
AddColumn<DocumentUrlDto>(Constants.DatabaseSchema.Tables.DocumentUrl, IsPrimaryColumnName);
}
}
}

View File

@@ -16,7 +16,7 @@ public class DocumentUrlDto
[PrimaryKeyColumn(Clustered = false, AutoIncrement = true)]
public int NodeId { get; set; }
[Index(IndexTypes.UniqueClustered, ForColumns = "uniqueId, languageId, isDraft", Name = "IX_" + TableName)]
[Index(IndexTypes.UniqueClustered, ForColumns = "uniqueId, languageId, isDraft, urlSegment", Name = "IX_" + TableName)]
[Column("uniqueId")]
[ForeignKey(typeof(NodeDto), Column = "uniqueId")]
public Guid UniqueId { get; set; }
@@ -28,14 +28,11 @@ public class DocumentUrlDto
[ForeignKey(typeof(LanguageDto))]
public int LanguageId { get; set; }
//
// [Column("segment")]
// [NullSetting(NullSetting = NullSettings.Null)]
// [Length(PropertyDataDto.SegmentLength)]
// public string Segment { get; set; } = string.Empty;
[Column("urlSegment")]
[NullSetting(NullSetting = NullSettings.NotNull)]
public string UrlSegment { get; set; } = string.Empty;
[Column("isPrimary")]
[Constraint(Default = 1)]
public bool IsPrimary { get; set; }
}

View File

@@ -1,18 +1,11 @@
using Microsoft.Extensions.Logging;
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Cms.Infrastructure.Persistence.Factories;
using Umbraco.Cms.Infrastructure.Scoping;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement;
public class DocumentUrlRepository : IDocumentUrlRepository
@@ -36,14 +29,15 @@ public class DocumentUrlRepository : IDocumentUrlRepository
public void Save(IEnumerable<PublishedDocumentUrlSegment> publishedDocumentUrlSegments)
{
//TODO avoid this is called as first thing on first restart after install
// TODO: avoid this is called as first thing on first restart after install
IEnumerable<Guid> documentKeys = publishedDocumentUrlSegments.Select(x => x.DocumentKey).Distinct();
Dictionary<(Guid UniqueId, int LanguageId, bool isDraft), DocumentUrlDto> dtoDictionary = publishedDocumentUrlSegments.Select(BuildDto).ToDictionary(x=> (x.UniqueId, x.LanguageId, x.IsDraft));
Dictionary<(Guid UniqueId, int LanguageId, bool isDraft, string urlSegment), DocumentUrlDto> dtoDictionary = publishedDocumentUrlSegments
.Select(BuildDto)
.ToDictionary(x => (x.UniqueId, x.LanguageId, x.IsDraft, x.UrlSegment));
var toUpdate = new List<DocumentUrlDto>();
var toDelete = new List<int>();
var toInsert = dtoDictionary.Values.ToDictionary(x => (x.UniqueId, x.LanguageId, x.IsDraft));
var toInsert = dtoDictionary.Values.ToDictionary(x => (x.UniqueId, x.LanguageId, x.IsDraft, x.UrlSegment));
foreach (IEnumerable<Guid> group in documentKeys.InGroupsOf(Constants.Sql.MaxParameterCount))
{
@@ -57,18 +51,12 @@ public class DocumentUrlRepository : IDocumentUrlRepository
foreach (DocumentUrlDto existing in existingUrlsInBatch)
{
if (dtoDictionary.TryGetValue((existing.UniqueId, existing.LanguageId, existing.IsDraft), out DocumentUrlDto? found))
if (dtoDictionary.TryGetValue((existing.UniqueId, existing.LanguageId, existing.IsDraft, existing.UrlSegment), out DocumentUrlDto? found))
{
found.NodeId = existing.NodeId;
// Only update if the url segment is different
if (found.UrlSegment != existing.UrlSegment)
{
toUpdate.Add(found);
}
// if we found it, we know we should not insert it as a new
toInsert.Remove((found.UniqueId, found.LanguageId, found.IsDraft));
// If we found it, we know we should not insert it as a new record.
toInsert.Remove((found.UniqueId, found.LanguageId, found.IsDraft, found.UrlSegment));
}
else
{
@@ -83,14 +71,6 @@ public class DocumentUrlRepository : IDocumentUrlRepository
Database.DeleteMany<DocumentUrlDto>().Where(x => toDelete.Contains(x.NodeId)).Execute();
}
if (toUpdate.Any())
{
foreach (DocumentUrlDto updated in toUpdate)
{
Database.Update(updated);
}
}
Database.InsertBulk(toInsert.Values);
}
@@ -115,7 +95,8 @@ public class DocumentUrlRepository : IDocumentUrlRepository
UrlSegment = dto.UrlSegment,
DocumentKey = dto.UniqueId,
LanguageId = dto.LanguageId,
IsDraft = dto.IsDraft
IsDraft = dto.IsDraft,
IsPrimary = dto.IsPrimary
};
private DocumentUrlDto BuildDto(PublishedDocumentUrlSegment model)
@@ -126,6 +107,7 @@ public class DocumentUrlRepository : IDocumentUrlRepository
UniqueId = model.DocumentKey,
LanguageId = model.LanguageId,
IsDraft = model.IsDraft,
IsPrimary = model.IsPrimary,
};
}
}

View File

@@ -1,6 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://learn.microsoft.com/dotnet/fundamentals/package-validation/diagnostic-ids -->
<Suppressions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Suppression>
<DiagnosticId>CP0001</DiagnosticId>
<Target>T:Umbraco.Cms.Tests.Integration.Umbraco.Core.Services.DocumentUrlServiceTest</Target>
<Left>lib/net9.0/Umbraco.Tests.Integration.dll</Left>
<Right>lib/net9.0/Umbraco.Tests.Integration.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0001</DiagnosticId>
<Target>T:Umbraco.Cms.Tests.Integration.Umbraco.Core.Services.DocumentUrlServiceTest_HideTopLevel_False</Target>
<Left>lib/net9.0/Umbraco.Tests.Integration.dll</Left>
<Right>lib/net9.0/Umbraco.Tests.Integration.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0001</DiagnosticId>
<Target>T:Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.PropertyEditors.BlockEditorBackwardsCompatibilityTests</Target>

View File

@@ -3,6 +3,7 @@ using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Testing;
@@ -13,9 +14,13 @@ namespace Umbraco.Cms.Tests.Integration.Umbraco.Core.Services;
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, Logger = UmbracoTestOptions.Logger.Mock)]
public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
public class DocumentUrlServiceTests : UmbracoIntegrationTestWithContent
{
private const string SubSubPage2Key = "48AE405E-5142-4EBE-929F-55EB616F51F2";
private const string SubSubPage3Key = "AACF2979-3F53-4184-B071-BA34D3338497";
protected IDocumentUrlService DocumentUrlService => GetRequiredService<IDocumentUrlService>();
protected ILanguageService LanguageService => GetRequiredService<ILanguageService>();
protected override void CustomTestSetup(IUmbracoBuilder builder)
@@ -24,8 +29,60 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
builder.AddNotificationHandler<ContentTreeChangeNotification, ContentTreeChangeDistributedCacheNotificationHandler>();
builder.Services.AddNotificationAsyncHandler<UmbracoApplicationStartingNotification, DocumentUrlServiceInitializerNotificationHandler>();
builder.UrlSegmentProviders().Insert<CustomUrlSegmentProvider1>();
builder.UrlSegmentProviders().Insert<CustomUrlSegmentProvider2>();
}
private abstract class CustomUrlSegmentProviderBase
{
private readonly IUrlSegmentProvider _defaultProvider;
public CustomUrlSegmentProviderBase(IShortStringHelper stringHelper) => _defaultProvider = new DefaultUrlSegmentProvider(stringHelper);
protected string? GetUrlSegment(IContentBase content, string? culture, params Guid[] pageKeys)
{
if (pageKeys.Contains(content.Key) is false)
{
return null;
}
var segment = _defaultProvider.GetUrlSegment(content, culture);
return segment is not null ? segment + "-custom" : null;
}
}
/// <summary>
/// A test implementation of <see cref="IUrlSegmentProvider"/> that provides a custom URL segment for a specific page
/// and allows for additional providers to provide segments too.
/// </summary>
private class CustomUrlSegmentProvider1 : CustomUrlSegmentProviderBase, IUrlSegmentProvider
{
public CustomUrlSegmentProvider1(IShortStringHelper stringHelper)
: base(stringHelper)
{
}
public bool AllowAdditionalSegments => true;
public string? GetUrlSegment(IContentBase content, string? culture = null)
=> GetUrlSegment(content, culture, Guid.Parse(SubPageKey), Guid.Parse(SubSubPage3Key));
}
/// <summary>
/// A test implementation of <see cref="IUrlSegmentProvider"/> that provides a custom URL segment for a specific page
/// and terminates, not allowing additional providers to provide segments too.
/// </summary>
private class CustomUrlSegmentProvider2 : CustomUrlSegmentProviderBase, IUrlSegmentProvider
{
public CustomUrlSegmentProvider2(IShortStringHelper stringHelper)
: base(stringHelper)
{
}
public string? GetUrlSegment(IContentBase content, string? culture = null)
=> GetUrlSegment(content, culture, Guid.Parse(SubPage2Key), Guid.Parse(SubSubPage2Key));
}
public override void Setup()
{
@@ -52,7 +109,7 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
// }
[Test]
public async Task Trashed_documents_do_not_have_a_url_segment()
public async Task GetUrlSegment_For_Deleted_Document_Does_Not_Have_Url_Segment()
{
var isoCode = (await LanguageService.GetDefaultLanguageAsync()).IsoCode;
@@ -64,7 +121,7 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
//TODO test with the urlsegment property value!
[Test]
public async Task Deleted_documents_do_not_have_a_url_segment__Parent_deleted()
public async Task GetUrlSegment_For_Document_With_Parent_Deleted_Does_Not_Have_Url_Segment()
{
ContentService.PublishBranch(Textpage, PublishBranchFilter.IncludeUnpublished, ["*"]);
@@ -78,7 +135,7 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
}
[Test]
public async Task Deleted_documents_do_not_have_a_url_segment()
public async Task GetUrlSegment_For_Published_Then_Deleted_Document_Does_Not_Have_Url_Segment()
{
ContentService.PublishBranch(Textpage, PublishBranchFilter.IncludeUnpublished, ["*"]);
@@ -91,16 +148,19 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
Assert.IsNull(actual);
}
[Test]
[TestCase("/", "en-US", true, ExpectedResult = TextpageKey)]
[TestCase("/text-page-1", "en-US", true, ExpectedResult = SubPageKey)]
[TestCase("/text-page-2", "en-US", true, ExpectedResult = SubPage2Key)]
[TestCase("/text-page-1-custom", "en-US", true, ExpectedResult = SubPageKey)] // Uses the segment registered by the custom IIUrlSegmentProvider that allows for more than one segment per document.
[TestCase("/text-page-2", "en-US", true, ExpectedResult = null)]
[TestCase("/text-page-2-custom", "en-US", true, ExpectedResult = SubPage2Key)] // Uses the segment registered by the custom IIUrlSegmentProvider that does not allow for more than one segment per document.
[TestCase("/text-page-3", "en-US", true, ExpectedResult = SubPage3Key)]
[TestCase("/", "en-US", false, ExpectedResult = TextpageKey)]
[TestCase("/text-page-1", "en-US", false, ExpectedResult = SubPageKey)]
[TestCase("/text-page-2", "en-US", false, ExpectedResult = SubPage2Key)]
[TestCase("/text-page-1-custom", "en-US", false, ExpectedResult = SubPageKey)] // Uses the segment registered by the custom IIUrlSegmentProvider that allows for more than one segment per document.
[TestCase("/text-page-2", "en-US", false, ExpectedResult = null)]
[TestCase("/text-page-2-custom", "en-US", false, ExpectedResult = SubPage2Key)] // Uses the segment registered by the custom IIUrlSegmentProvider that does not allow for more than one segment per document.
[TestCase("/text-page-3", "en-US", false, ExpectedResult = SubPage3Key)]
public string? Expected_Routes(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Returns_Expected_Route(string route, string isoCode, bool loadDraft)
{
if (loadDraft is false)
{
@@ -111,16 +171,16 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
}
[Test]
public void No_Published_Route_when_not_published()
public void GetDocumentKeyByRoute_UnPublished_Documents_Have_No_Published_Route()
{
Assert.IsNotNull(DocumentUrlService.GetDocumentKeyByRoute("/text-page-1", "en-US", null, true));
Assert.IsNull(DocumentUrlService.GetDocumentKeyByRoute("/text-page-1", "en-US", null, false));
}
[Test]
public void Unpublished_Pages_Are_not_available()
public void GetDocumentKeyByRoute_Published_Then_Unpublished_Documents_Have_No_Published_Route()
{
//Arrange
// Arrange
ContentService.PublishBranch(Textpage, PublishBranchFilter.IncludeUnpublished, ["*"]);
Assert.Multiple(() =>
@@ -131,7 +191,7 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
Assert.IsNotNull(DocumentUrlService.GetDocumentKeyByRoute("/text-page-1", "en-US", null, false));
});
//Act
// Act
ContentService.Unpublish(Textpage );
Assert.Multiple(() =>
@@ -144,18 +204,32 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
Assert.IsNotNull(DocumentUrlService.GetDocumentKeyByRoute("/text-page-1", "en-US", null, true));
Assert.IsNull(DocumentUrlService.GetDocumentKeyByRoute("/text-page-1", "en-US", null, false));
});
}
[Test]
[TestCase("/text-page-1/sub-page-1", "en-US", true, ExpectedResult = "DF49F477-12F2-4E33-8563-91A7CC1DCDBB")]
[TestCase("/text-page-1/sub-page-1", "en-US", false, ExpectedResult = "DF49F477-12F2-4E33-8563-91A7CC1DCDBB")]
public string? Expected_Routes_with_subpages(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Returns_Expected_Route_For_SubPage(string route, string isoCode, bool loadDraft)
=> ExecuteSubPageTest("DF49F477-12F2-4E33-8563-91A7CC1DCDBB", "Sub Page 1", route, isoCode, loadDraft);
[TestCase("/text-page-1/sub-page-2-custom", "en-US", true, ExpectedResult = SubSubPage2Key)]
[TestCase("/text-page-1/sub-page-2-custom", "en-US", false, ExpectedResult = SubSubPage2Key)]
[TestCase("/text-page-1/sub-page-2", "en-US", true, ExpectedResult = null)]
[TestCase("/text-page-1/sub-page-2", "en-US", false, ExpectedResult = null)]
public string? GetDocumentKeyByRoute_Returns_Expected_Route_For_SubPage_With_Terminating_Custom_Url_Provider(string route, string isoCode, bool loadDraft)
=> ExecuteSubPageTest(SubSubPage2Key, "Sub Page 2", route, isoCode, loadDraft);
[TestCase("/text-page-1/sub-page-3-custom", "en-US", true, ExpectedResult = SubSubPage3Key)]
[TestCase("/text-page-1/sub-page-3-custom", "en-US", false, ExpectedResult = SubSubPage3Key)]
[TestCase("/text-page-1/sub-page-3", "en-US", true, ExpectedResult = SubSubPage3Key)]
[TestCase("/text-page-1/sub-page-3", "en-US", false, ExpectedResult = SubSubPage3Key)]
public string? GetDocumentKeyByRoute_Returns_Expected_Route_For_SubPage_With_Non_Terminating_Custom_Url_Provider(string route, string isoCode, bool loadDraft)
=> ExecuteSubPageTest(SubSubPage3Key, "Sub Page 3", route, isoCode, loadDraft);
private string? ExecuteSubPageTest(string documentKey, string documentName, string route, string isoCode, bool loadDraft)
{
// Create a subpage
var subsubpage = ContentBuilder.CreateSimpleContent(ContentType, "Sub Page 1", Subpage.Id);
subsubpage.Key = new Guid("DF49F477-12F2-4E33-8563-91A7CC1DCDBB");
var subsubpage = ContentBuilder.CreateSimpleContent(ContentType, documentName, Subpage.Id);
subsubpage.Key = Guid.Parse(documentKey);
var contentSchedule = ContentScheduleCollection.CreateWithEntry(DateTime.Now.AddMinutes(-5), null);
ContentService.Save(subsubpage, -1, contentSchedule);
@@ -164,13 +238,12 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
ContentService.PublishBranch(Textpage, PublishBranchFilter.IncludeUnpublished, ["*"]);
}
return DocumentUrlService.GetDocumentKeyByRoute(route, isoCode, null, loadDraft)?.ToString()?.ToUpper();
return DocumentUrlService.GetDocumentKeyByRoute(route, isoCode, null, loadDraft)?.ToString()?.ToUpper();
}
[Test]
[TestCase("/second-root", "en-US", true, ExpectedResult = "8E21BCD4-02CA-483D-84B0-1FC92702E198")]
[TestCase("/second-root", "en-US", false, ExpectedResult = "8E21BCD4-02CA-483D-84B0-1FC92702E198")]
public string? Second_root_cannot_hide_url(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Second_Root_Does_Not_Hide_Url(string route, string isoCode, bool loadDraft)
{
// Create a second root
var secondRoot = ContentBuilder.CreateSimpleContent(ContentType, "Second Root", null);
@@ -187,10 +260,9 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
return DocumentUrlService.GetDocumentKeyByRoute(route, isoCode, null, loadDraft)?.ToString()?.ToUpper();
}
[Test]
[TestCase("/child-of-second-root", "en-US", true, ExpectedResult = "FF6654FB-BC68-4A65-8C6C-135567F50BD6")]
[TestCase("/child-of-second-root", "en-US", false, ExpectedResult = "FF6654FB-BC68-4A65-8C6C-135567F50BD6")]
public string? Child_of_second_root_do_not_have_parents_url_as_prefix(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Child_Of_Second_Root_Does_Not_Have_Parents_Url_As_Prefix(string route, string isoCode, bool loadDraft)
{
// Create a second root
var secondRoot = ContentBuilder.CreateSimpleContent(ContentType, "Second Root", null);
@@ -205,7 +277,6 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
// Publish both the main root and the second root with descendants
if (loadDraft is false)
{
ContentService.PublishBranch(Textpage, PublishBranchFilter.IncludeUnpublished, ["*"]);
ContentService.PublishBranch(secondRoot, PublishBranchFilter.IncludeUnpublished, ["*"]);
}
@@ -213,6 +284,16 @@ public class DocumentUrlServiceTest : UmbracoIntegrationTestWithContent
return DocumentUrlService.GetDocumentKeyByRoute(route, isoCode, null, loadDraft)?.ToString()?.ToUpper();
}
[TestCase(TextpageKey, "en-US", ExpectedResult = "/")]
[TestCase(SubPageKey, "en-US", ExpectedResult = "/text-page-1-custom")] // Has non-terminating custom URL segment provider.
[TestCase(SubPage2Key, "en-US", ExpectedResult = "/text-page-2-custom")] // Has terminating custom URL segment provider.
[TestCase(SubPage3Key, "en-US", ExpectedResult = "/text-page-3")]
public string? GetLegacyRouteFormat_Returns_Expected_Route(string documentKey, string culture)
{
ContentService.PublishBranch(Textpage, PublishBranchFilter.IncludeUnpublished, ["*"]);
return DocumentUrlService.GetLegacyRouteFormat(Guid.Parse(documentKey), culture, false);
}
//TODO test cases:
// - Find the root, when a domain is set

View File

@@ -2,12 +2,10 @@ using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Handlers;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Tests.Common.Attributes;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
@@ -17,7 +15,7 @@ namespace Umbraco.Cms.Tests.Integration.Umbraco.Core.Services;
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, Logger = UmbracoTestOptions.Logger.Console)]
public class DocumentUrlServiceTest_HideTopLevel_False : UmbracoIntegrationTestWithContent
public class DocumentUrlServiceTests_HideTopLevel_False : UmbracoIntegrationTestWithContent
{
protected IDocumentUrlService DocumentUrlService => GetRequiredService<IDocumentUrlService>();
protected ILanguageService LanguageService => GetRequiredService<ILanguageService>();
@@ -28,7 +26,6 @@ public class DocumentUrlServiceTest_HideTopLevel_False : UmbracoIntegrationTestW
builder.Services.AddUnique<IServerMessenger, ScopedRepositoryTests.LocalServerMessenger>();
builder.AddNotificationHandler<ContentTreeChangeNotification, ContentTreeChangeDistributedCacheNotificationHandler>();
}
public override void Setup()
@@ -46,7 +43,7 @@ public class DocumentUrlServiceTest_HideTopLevel_False : UmbracoIntegrationTestW
[TestCase("/textpage/text-page-1", "en-US", false, ExpectedResult = SubPageKey)]
[TestCase("/textpage/text-page-2", "en-US", false, ExpectedResult = SubPage2Key)]
[TestCase("/textpage/text-page-3", "en-US", false, ExpectedResult = SubPage3Key)]
public string? Expected_Routes(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Returns_Expected_Route(string route, string isoCode, bool loadDraft)
{
if (loadDraft is false)
{
@@ -60,7 +57,7 @@ public class DocumentUrlServiceTest_HideTopLevel_False : UmbracoIntegrationTestW
[Test]
[TestCase("/textpage/text-page-1/sub-page-1", "en-US", true, ExpectedResult = "DF49F477-12F2-4E33-8563-91A7CC1DCDBB")]
[TestCase("/textpage/text-page-1/sub-page-1", "en-US", false, ExpectedResult = "DF49F477-12F2-4E33-8563-91A7CC1DCDBB")]
public string? Expected_Routes_with_subpages(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Returns_Expected_Route_For_SubPage(string route, string isoCode, bool loadDraft)
{
// Create a subpage
var subsubpage = ContentBuilder.CreateSimpleContent(ContentType, "Sub Page 1", Subpage.Id);
@@ -79,7 +76,7 @@ public class DocumentUrlServiceTest_HideTopLevel_False : UmbracoIntegrationTestW
[Test]
[TestCase("/second-root", "en-US", true, ExpectedResult = "8E21BCD4-02CA-483D-84B0-1FC92702E198")]
[TestCase("/second-root", "en-US", false, ExpectedResult = "8E21BCD4-02CA-483D-84B0-1FC92702E198")]
public string? Second_root_cannot_hide_url(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Second_Root_Does_Not_Hide_Url(string route, string isoCode, bool loadDraft)
{
// Create a second root
var secondRoot = ContentBuilder.CreateSimpleContent(ContentType, "Second Root", null);
@@ -99,7 +96,7 @@ public class DocumentUrlServiceTest_HideTopLevel_False : UmbracoIntegrationTestW
[Test]
[TestCase("/second-root/child-of-second-root", "en-US", true, ExpectedResult = "FF6654FB-BC68-4A65-8C6C-135567F50BD6")]
[TestCase("/second-root/child-of-second-root", "en-US", false, ExpectedResult = "FF6654FB-BC68-4A65-8C6C-135567F50BD6")]
public string? Child_of_second_root_do_not_have_parents_url_as_prefix(string route, string isoCode, bool loadDraft)
public string? GetDocumentKeyByRoute_Child_Of_Second_Root_Does_Not_Have_Parents_Url_As_Prefix(string route, string isoCode, bool loadDraft)
{
// Create a second root
var secondRoot = ContentBuilder.CreateSimpleContent(ContentType, "Second Root", null);