diff --git a/.gitignore b/.gitignore index c5f1728..1985da3 100644 --- a/.gitignore +++ b/.gitignore @@ -68,3 +68,4 @@ vcpkg_installed/ # test output & cache Testing/ .cache/ +*out* \ No newline at end of file diff --git a/README.md b/README.md index 20b8070..057cf28 100644 --- a/README.md +++ b/README.md @@ -34,39 +34,35 @@ void create_example_ro_crate() { // this is currently missing // Get the root metadata entity from the crate and set the description - Entity root = crate.getEntity("ro-crate-metadata.json"); + Entity& root = crate.getEntity("ro-crate-metadata.json"); root.set("description", "RO-Crate Metadata File Descriptor (this file)"); // Add name, description to the root data entity (./) - Entity rootData = crate.getEntity("./"); + Entity& rootData = crate.getEntity("./"); rootData.set("name", "Example RO-Crate"); rootData.set("description", "The RO-Crate Root Data Entity"); // -------------------------------------------------------------------------- // Create the person, which is a contextual entity, and add it to the crate - Entity alice({"Person"}); + Entity& alice = crate.createEntity("#alice", {"Person"}); alice.set("name", "Alice"); alice.set("description", "One of hopefully many Contextual Entities"); - crate.addEntity("#alice", alice); // -------------------------------------------------------------------------- // Create the place, another contextual entity, and add it to the crate - Entity catalinaPark({"Place"}); + Entity& catalinaPark = crate.createEntity("http://sws.geonames.org/8152662/", {"Place"}); catalinaPark.set("name", "Catalina Park"); - crate.addEntity("http://sws.geonames.org/8152662/", catalinaPark); // -------------------------------------------------------------------------- // Create two datasets, which are data entities, and add them to the crate. - Entity data1({"File"}); + Entity& data1 = crate.createEntity("data1.txt", {"File"}); data1.set("description", "One of hopefully many Data Entities"); data1.set("author", alice); data1.set("contentLocation", catalinaPark); - crate.addEntity("data1.txt", data1); rootData.set("hasPart", data1); // Ensure that the root data entity has a hasPart relationship to data1 - Entity data2({"File"}); - crate.addEntity("data2.txt", data2); + Entity& data2 = crate.createEntity("data2.txt", {"File"}); rootData.set("hasPart", data2); // -------------------------------------------------------------------------- @@ -94,49 +90,72 @@ root data entity (./). ROCrate crate; ``` -### Create an Entity +### Create an Entity -To create an entity, instantiate the `Entity` class. You must provide a type, -or can provide a list of types. +Entities are always owned by an RO-Crate: creating one and adding it to the +crate happen in a single step, via the `createEntity` method on `ROCrate`. The +first argument is the entity ID, and the second is a type, or list of types. +`createEntity` constructs the entity and returns a mutable reference to it. ```cpp +ROCrate crate; + // Single type -Entity alice({"Person"}); +Entity& alice = crate.createEntity("#alice", {"Person"}); // Multiple types -Entity data1({"File", "Dataset"}); +Entity& data1 = crate.createEntity("data1.txt", {"File", "Dataset"}); ``` ### Add properties to an Entity -To add properties to an entity, use the `set` method. The first argument is the -property name, and the second argument is the property value. The property value -can either be a string, or another entity. +To add properties to an entity, use the `set` method on the reference returned +by `createEntity` (or `getEntity`). The first argument is the property name, and +the second argument is the property value. The property value can either be a +string, or another entity. If a string property value is provided, it create a straightforward key-value pair in the entity e.g. `name: "Alice"`. If an entity is provided, it will create a relationship between the two entities e.g. `author: { "@id": "#alice" }`. ```cpp +ROCrate crate; + // Add a string property -Entity alice({"Person"}); +Entity& alice = crate.createEntity("#alice", {"Person"}); alice.set("name", "Alice"); // Add a relationship property -Entity data1({"File"}); +Entity& data1 = crate.createEntity("data1.txt", {"File"}); data1.set("author", alice); ``` -### Add an Entity to an RO-Crate +You can also bulk add properties to an entity by passing a map of property names +and values to the `set` method. + +```cpp +ROCrate crate; +Entity& alice = crate.createEntity("#alice", {"Person"}); +std::map properties = { + {"name", "Alice"}, + {"description", "One of hopefully many Contextual Entities"} +}; +``` + +### Get properties of an Entity -To add an entity to an RO-Crate, use the `addEntity` method. The first argument is -the entity ID, and the second argument is the entity object. +To get properties of an entity, use the `getProperty` method on the reference returned by `createEntity` (or `getEntity`). ```cpp ROCrate crate; +Entity& alice = crate.createEntity("#alice", {"Person"}); +alice.set("name", "Alice"); -Entity alice({"Person"}); -crate.addEntity("#alice", alice); +for (const auto& [property, values] : alice.getProperties()) { + for (const auto& value : values) { + std::cout << property << ": " << value.value << "\n"; + } +} ``` ### Add additional context to an RO-Crate @@ -175,25 +194,19 @@ relationships between entities. ### Entity lifecycle -When an entity is created, it is not automatically added to the RO-Crate. The user -must explicitly add the entity to the RO-Crate using the `addEntity` method. - -When an entity is added to the RO-Crate, it is stored in a map of entities. - -For maximum flexiblity, an already added entity may still be updated on the -original entity object. The RO-Crate shares the same entity object, so any changes -made to the original entity will be reflected in the RO-Crate. +An entity cannot exist independently of an RO-Crate: it is always constructed +and owned by the crate's entity register, via `ROCrate::createEntity`. This method +returns a mutable reference to the entity, which can be used to set further +properties, or passed to `set` on other entities to create relationships. Worked example: ```cpp ROCrate crate; -Entity alice({"Person"}); +Entity& alice = crate.createEntity("#alice", {"Person"}); alice.set("name", "Alice"); -crate.addEntity("#alice", alice); - /* Crate state: { "#alice": { @@ -203,12 +216,9 @@ crate.addEntity("#alice", alice); } */ -// Add an additional property to the crate entity -Entity crateAlice = crate.getEntity("#alice"); -crateAlice.set("description", "One of hopefully many Contextual Entities"); - -// Add an additional property to the original entity object -alice.set("occupation", "Software Engineer"); +// Further updates go through the same reference, or a fresh one from getEntity +alice.set("description", "One of hopefully many Contextual Entities"); +crate.getEntity("#alice").set("occupation", "Software Engineer"); /* Crate state: { @@ -222,6 +232,11 @@ alice.set("occupation", "Software Engineer"); */ ``` +Note that `getEntity` and `createEntity` both return references (`Entity&`). +Copying the result into a plain `Entity` variable (rather than binding a +reference) makes an independent copy that will not reflect further changes, +and will not itself reflect changes made to the crate's entity afterwards. + ## Reference Reference documentation generated by [doxide](doxide.org) is available [here](http://esciencelab.org.uk/ro-crate-cpp/). diff --git a/docs/rocrate/Entity.md b/docs/rocrate/Entity.md index e803fed..d767b89 100644 --- a/docs/rocrate/Entity.md +++ b/docs/rocrate/Entity.md @@ -11,15 +11,21 @@ Represents an entity in the RO-Crate. An entity can have multiple types and properties, where each property can have multiple values. Properties can be set as either literal values or references to other entities. +Entities are created and added via ROCrate::createEntity, +which constructs the Entity and returns a mutable reference to it. + ## Functions | Name | Description | | ---- | ----------- | -| [Entity](#Entity) | Constructs an Entity with the specified types. | | [set](#set) | Sets a property-value pair for the entity. | | [set](#set) | Sets a property to reference another entity. | +| [set](#set) | Sets multiple properties for the entity at once. | +| [getProperties](#getProperties) | Retrieves the properties of the entity. | +| [Entity](#Entity) | Constructs an Entity with the specified types. | | [assignId](#assignId) | Assigns an '@id' to the entity. | +| [validateSetRequest](#validateSetRequest) | Validates a set request for a property-value pair. | ## Function Details @@ -28,6 +34,9 @@ Properties can be set as either literal values or references to other entities. Constructs an Entity with the specified types. + Private since entities are always constructed and owned by an RO-Crate + via ROCrate::createEntity. + :material-location-enter: `types` : A vector of strings representing the types of the entity. @@ -49,8 +58,18 @@ Properties can be set as either literal values or references to other entities. : std::invalid_argument if the id is empty. +### getProperties +!!! function "Properties getProperties() const" + + Retrieves the properties of the entity. + + + :material-keyboard-return: **Return** + : A copy of the properties map, where each property maps to a vector of PropertyValue objects. + + ### set -!!! function "void set( Property property, Value value, ValueType type = ValueType::Literal )" +!!! function "void set(Property property, Value value, ValueType type = ValueType::Literal)" Sets a property-value pair for the entity. @@ -86,3 +105,31 @@ Properties can be set as either literal values or references to other entities. : std::runtime_error if the referenced entity does not have an '@id' property set. +!!! function "void set(std::map<Property, Value> properties)" + + Sets multiple properties for the entity at once. + + + :material-location-enter: `properties` + : A map of property names to their corresponding values. + + :material-alert-circle-outline: **Throw** + : std::invalid_argument if any property name or value is empty, or if attempting to set '@id' directly. + + +### validateSetRequest +!!! function "void validateSetRequest(Property property, Value value)" + + Validates a set request for a property-value pair. + + + :material-location-enter: `property` + : The name of the property to validate. + + :material-location-enter: `value` + : The value to validate. + + :material-alert-circle-outline: **Throw** + : std::invalid_argument if the property name or value is empty, or if attempting to set '@id' directly. + + diff --git a/docs/rocrate/ROCrate.md b/docs/rocrate/ROCrate.md index bf77fec..bf296b9 100644 --- a/docs/rocrate/ROCrate.md +++ b/docs/rocrate/ROCrate.md @@ -18,27 +18,52 @@ It provides methods to add entities, retrieve entities by their identifiers, and | Name | Description | | ---- | ----------- | | [ROCrate](#ROCrate) | Constructs an RO-Crate with a root metadata entity and a root dataset entity. | -| [addEntity](#addEntity) | Adds an entity to the RO-Crate's entity register with the specified id. | +| [createEntity](#createEntity) | Constructs an entity with the given types and adds it to the RO-Crate's entity register. | +| [hasEntity](#hasEntity) | Checks if an entity with the specified id exists in the RO-Crate's entity register. | | [getEntity](#getEntity) | Retrieves an entity from the RO-Crate's entity register by its id. | -| [addContext](#addContext) | Adds a context entry to the RO-Crate's root metadata entity. | +| [getEntities](#getEntities) | Gets the register of entities in the RO-Crate. | +| [addContext](#addContext) | Adds a context entry to the RO-Crate's root metadata entity, without a prefix. | +| [addContext](#addContext) | Adds a context entry to the RO-Crate's root metadata entity, with a prefix. | +| [getContext](#getContext) | Retrieves the context entries :material-keyboard-return: **Return** : A copy of the context entries map | +| [getRemoteContext](#getRemoteContext) | Retrieves the remote context entries :material-keyboard-return: **Return** : A copy of the remote context entries vector | | [writeOut](#writeOut) | Serializes the RO-Crate to a JSON file at the specified path. | | [readIn](#readIn) | Reads an RO-Crate from a JSON file at the specified path and populates the current RO-Crate instance with the entities and context from the file. | ## Function Details ### ROCrate -!!! function "ROCrate()" +!!! function "ROCrate(std::string rootDataEntityId = "./")" Constructs an RO-Crate with a root metadata entity and a root dataset entity. The constructor initializes the RO-Crate with an empty entity register, creates the root metadata entity (ro-crate-metadata.json) and the root dataset entity, and adds the root dataset entity to the root metadata entity. + If no rootDataEntityId is provided, a standard RO-Crate is produced, if + a rootDataEntityId is provided, a detached RO-Crate is produced, assuming + that rootDataEntityId is a valid URI + + + :material-location-enter: `rootDataEntityId` + : The identifier for the root dataset entity. Defaults to "./" if not provided. + ### addContext +!!! function "void addContext(const std::string& value)" + + Adds a context entry to the RO-Crate's root metadata entity, without a prefix. + + + :material-location-enter: `value` + : The context value associated with the key. + + :material-alert-circle-outline: **Throw** + : std::invalid_argument if the value is empty. + + !!! function "void addContext(const std::string& key, const std::string& value)" - Adds a context entry to the RO-Crate's root metadata entity. + Adds a context entry to the RO-Crate's root metadata entity, with a prefix. :material-location-enter: `key` @@ -51,25 +76,48 @@ It provides methods to add entities, retrieve entities by their identifiers, and : std::invalid_argument if the key or value is empty. -### addEntity -!!! function "void addEntity(const std::string& id, Entity& entity)" +### createEntity +!!! function "Entity& createEntity(const std::string& id, std::vector<std::string> types)" - Adds an entity to the RO-Crate's entity register with the specified id. + Constructs an entity with the given types and adds it to the RO-Crate's entity register. :material-location-enter: `id` : The identifier for the entity. - :material-location-enter: `entity` - : The entity to add to the RO-Crate. + :material-location-enter: `types` + : A vector of strings representing the types of the entity. + + :material-keyboard-return: **Return** + : A mutable reference to the newly created entity, now owned by the RO-Crate. :material-alert-circle-outline: **Throw** - : std::invalid_argument if the id is empty. + : std::invalid_argument if the id is empty, or if the types vector is empty. :material-alert-circle-outline: **Throw** : std::runtime_error if an entity with the given id already exists in the RO-Crate. +### getContext +!!! function "std::map<std::string, std::string> getContext() const" + + Retrieves the context entries + + + :material-keyboard-return: **Return** + : A copy of the context entries map + + +### getEntities +!!! function "EntityRegister getEntities() const" + + Gets the register of entities in the RO-Crate. + + + :material-keyboard-return: **Return** + : A copy of the entity register + + ### getEntity !!! function "Entity& getEntity(const std::string& id)" @@ -83,7 +131,30 @@ It provides methods to add entities, retrieve entities by their identifiers, and : A reference to the entity with the specified id. :material-alert-circle-outline: **Throw** - : std::runtime_error if no entity with the given id is found in the RO-Crate. + : std::runtime_error if no entity with the given id exists in the RO-Crate. + + +### getRemoteContext +!!! function "std::vector<std::string> getRemoteContext() const" + + Retrieves the remote context entries + + + :material-keyboard-return: **Return** + : A copy of the remote context entries vector + + +### hasEntity +!!! function "bool hasEntity(const std::string& id)" + + Checks if an entity with the specified id exists in the RO-Crate's entity register. + + + :material-location-enter: `id` + : The identifier of the entity to check. + + :material-keyboard-return: **Return** + : true if an entity with the given id exists, false otherwise. ### readIn diff --git a/docs/rocrate/index.md b/docs/rocrate/index.md index 062ba20..15bc9ff 100644 --- a/docs/rocrate/index.md +++ b/docs/rocrate/index.md @@ -14,18 +14,3 @@ generator: doxide | [Entity](Entity.md) | Represents an entity in the RO-Crate. | | [ROCrate](ROCrate.md) | Represents an RO-Crate, a structured collection of entities and metadata. | -## Functions - -| Name | Description | -| ---- | ----------- | -| [error_message](#error_message) | Returns the message template for the given error code. | - -## Function Details - -### error_message -!!! function "constexpr std::string_view error_message(ErrorCode code)" - - Returns the message template for the given error code. - Templates with placeholders are substituted via std::format at the throw site. - - diff --git a/include/ro-crate.hpp b/include/ro-crate.hpp index 538b8f4..469eb96 100644 --- a/include/ro-crate.hpp +++ b/include/ro-crate.hpp @@ -3,11 +3,11 @@ #include #include -#include #include #include #include #include +#include namespace rocrate { @@ -30,19 +30,14 @@ namespace rocrate { * Represents an entity in the RO-Crate. * An entity can have multiple types and properties, where each property can have multiple values. * Properties can be set as either literal values or references to other entities. + * + * Entities are created and added via ROCrate::createEntity, + * which constructs the Entity and returns a mutable reference to it. */ class Entity { - + public: Entity() = delete; - - /** - * Constructs an Entity with the specified types. - * - * @param types A vector of strings representing the types of the entity. - * @throw std::invalid_argument if the types vector is empty. - */ - explicit Entity(std::vector types); ~Entity() = default; /** @@ -53,25 +48,47 @@ namespace rocrate { * @param valueType The type of the value (Literal or Reference). * @throw std::invalid_argument if the property name or value is empty, or if attempting to set '@id' directly. */ - void set( - Property property, - Value value, - ValueType type = ValueType::Literal - ); - + void set(Property property, Value value, ValueType type = ValueType::Literal); + /** - * Sets a property to reference another entity. - * - * @param property The name of the property to set. - * @param entity The entity to reference. - * @throw std::invalid_argument if the property name is empty. - * @throw std::runtime_error if the referenced entity does not have an '@id' property set. - */ + * Sets a property to reference another entity. + * + * @param property The name of the property to set. + * @param entity The entity to reference. + * @throw std::invalid_argument if the property name is empty. + * @throw std::runtime_error if the referenced entity does not have an '@id' property set. + */ void set(Property property, const Entity& entity); + /** + * Sets multiple properties for the entity at once. + * + * @param properties A map of property names to their corresponding values. + * @throw std::invalid_argument if any property name or value is empty, or if attempting to set '@id' directly. + */ + void set(std::map properties); + + /** + * Retrieves the properties of the entity. + * + * @return A copy of the properties map, where each property maps to a vector of PropertyValue objects. + */ + Properties getProperties() const; + private: friend class ROCrate; + /** + * Constructs an Entity with the specified types. + * + * Private since entities are always constructed and owned by an RO-Crate + * via ROCrate::createEntity. + * + * @param types A vector of strings representing the types of the entity. + * @throw std::invalid_argument if the types vector is empty. + */ + explicit Entity(std::vector types); + /** * Assigns an '@id' to the entity. * @@ -79,37 +96,49 @@ namespace rocrate { * @throw std::invalid_argument if the id is empty. */ void assignId(const std::string& id); - std::shared_ptr properties_; - }; - inline Entity::Entity(std::vector types) - : properties_(std::make_shared()) { + /** + * Validates a set request for a property-value pair. + * + * @param property The name of the property to validate. + * @param value The value to validate. + * @throw std::invalid_argument if the property name or value is empty, or if attempting to set '@id' directly. + */ + void validateSetRequest(Property property, Value value); + Properties properties_; + }; + + inline Entity::Entity(std::vector types) { // Validate types (reject empty) if ( types.empty() ) { throw std::invalid_argument("Entity must have at least one type."); } - + // Set the types of the entity std::vector typeValues; for (const auto& type : types) typeValues.push_back({type, ValueType::Literal}); - properties_->emplace("@type", typeValues); + properties_.emplace("@type", typeValues); } - - inline void Entity::set(Property property, Value value, ValueType valueType) { - // Validate property and value + + inline void Entity::validateSetRequest(Property property, Value value) { if (property.empty()) throw std::invalid_argument("Property name cannot be empty."); if (value.empty()) throw std::invalid_argument("Property value cannot be empty."); if (property == "@id") throw std::invalid_argument("Cannot set '@id' property directly. " - "Use ROCrate::addEntity to assign an ID."); + "Use ROCrate::createEntity to assign an ID."); + } + inline void Entity::set(Property property, Value value, ValueType valueType) { + // Validate property and value + validateSetRequest(property, value); + // Check property is not duplicate - ignore if so - auto it = properties_->find(property); - if (it != properties_->end()) { + auto it = properties_.find(property); + if (it != properties_.end()) { for (const auto& existingValue : it->second) { if (existingValue.value == value && existingValue.type == valueType) { // Duplicate found, ignore @@ -119,7 +148,7 @@ namespace rocrate { } // Add the value to the property in the properties map - (*properties_)[property].push_back({value, valueType}); + properties_[property].push_back({value, valueType}); } inline void Entity::set(Property property, const Entity& entity) { @@ -129,14 +158,28 @@ namespace rocrate { } // Check if the entity has an '@id' property set - const auto id = entity.properties_->find("@id"); - if (id == entity.properties_->end() || id->second.empty()) + const auto id = entity.properties_.find("@id"); + if (id == entity.properties_.end() || id->second.empty()) throw std::runtime_error("Entity does not have an '@id' property set."); // Add JSON reference to the entity's '@id' to the property in the properties map set(property, id->second.front().value, ValueType::Reference); } + inline void Entity::set(std::map properties) { + for (const auto& [property, value] : properties) { + validateSetRequest(property, value); + } + + for (const auto& [property, value] : properties) { + set(property, value, ValueType::Literal); + } + } + + inline Properties Entity::getProperties() const { + return properties_; + } + inline void Entity::assignId(const std::string& id) { // Validate id if (id.empty()) { @@ -144,7 +187,7 @@ namespace rocrate { } // Assign the '@id' property to the entity's properties map - (*properties_)["@id"] = {{id, ValueType::Literal}}; + properties_["@id"] = {{id, ValueType::Literal}}; } // --------------------------------------------------------------------------- @@ -166,30 +209,60 @@ namespace rocrate { * * The constructor initializes the RO-Crate with an empty entity register, creates the root metadata entity * (ro-crate-metadata.json) and the root dataset entity, and adds the root dataset entity to the root metadata entity. + * + * If no rootDataEntityId is provided, a standard RO-Crate is produced, if + * a rootDataEntityId is provided, a detached RO-Crate is produced, assuming + * that rootDataEntityId is a valid URI + * + * @param rootDataEntityId The identifier for the root dataset entity. Defaults to "./" if not provided. */ - ROCrate(); + ROCrate(std::string rootDataEntityId = "./"); /** - * Adds an entity to the RO-Crate's entity register with the specified id. + * Constructs an entity with the given types and adds it to the RO-Crate's entity register. * * @param id The identifier for the entity. - * @param entity The entity to add to the RO-Crate. - * @throw std::invalid_argument if the id is empty. + * @param types A vector of strings representing the types of the entity. + * @return A mutable reference to the newly created entity, now owned by the RO-Crate. + * @throw std::invalid_argument if the id is empty, or if the types vector is empty. * @throw std::runtime_error if an entity with the given id already exists in the RO-Crate. */ - void addEntity(const std::string& id, Entity& entity); + Entity& createEntity(const std::string& id, std::vector types); + + /** + * Checks if an entity with the specified id exists in the RO-Crate's entity register. + * + * @param id The identifier of the entity to check. + * @return true if an entity with the given id exists, false otherwise. + */ + bool hasEntity(const std::string& id); /** - * Retrieves an entity from the RO-Crate's entity register by its id. + * Retrieves an entity from the RO-Crate's entity register by its id. + * + * @param id The identifier of the entity to retrieve. + * @return A reference to the entity with the specified id. + * @throw std::runtime_error if no entity with the given id exists in the RO-Crate. + */ + Entity& getEntity(const std::string& id); + + /** + * Gets the register of entities in the RO-Crate. * - * @param id The identifier of the entity to retrieve. - * @return A reference to the entity with the specified id. - * @throw std::runtime_error if no entity with the given id is found in the RO-Crate. + * @return A copy of the entity register */ - Entity& getEntity(const std::string& id); + EntityRegister getEntities() const; /** - * Adds a context entry to the RO-Crate's root metadata entity. + * Adds a context entry to the RO-Crate's root metadata entity, without a prefix. + * + * @param value The context value associated with the key. + * @throw std::invalid_argument if the value is empty. + */ + void addContext(const std::string& value); + + /** + * Adds a context entry to the RO-Crate's root metadata entity, with a prefix. * * @param key The context key to add. * @param value The context value associated with the key. @@ -197,6 +270,20 @@ namespace rocrate { */ void addContext(const std::string& key, const std::string& value); + /** + * Retrieves the context entries + * + * @return A copy of the context entries map + */ + std::map getContext() const; + + /** + * Retrieves the remote context entries + * + * @return A copy of the remote context entries vector + */ + std::vector getRemoteContext() const; + /** * Serializes the RO-Crate to a JSON file at the specified path. * @@ -234,31 +321,31 @@ namespace rocrate { ); EntityRegister entities_; + std::vector remoteContext_ = { + "https://w3id.org/ro/crate/1.3/context", + }; std::map context_; }; - inline ROCrate::ROCrate() { + inline ROCrate::ROCrate(std::string rootDataEntityId) { // Initialise the RO-Crate with an empty entity register entities_ = {}; - // Create the root metadata entity (ro-crate-metadata.json) - Entity rootEntity({"CreativeWork"}); + // Create the root metadata entity (ro-crate-metadata.json) and the root dataset entity + Entity& rootEntity = createEntity("ro-crate-metadata.json", {"CreativeWork"}); + Entity& datasetEntity = createEntity(rootDataEntityId, {"Dataset"}); + rootEntity.set( "conformsTo", "https://w3id.org/ro/crate/1.3", ValueType::Reference ); - addEntity("ro-crate-metadata.json", rootEntity); - - // Create the root dataset entity - Entity datasetEntity({"Dataset"}); - addEntity("./", datasetEntity); // Add the root dataset entity to the root metadata entity rootEntity.set("about", datasetEntity); } - inline void ROCrate::addEntity(const std::string& id, Entity& entity) { + inline Entity& ROCrate::createEntity(const std::string& id, std::vector types) { // Validate the id (reject empty) if (id.empty()) { throw std::invalid_argument("Entity ID cannot be empty."); @@ -268,12 +355,18 @@ namespace rocrate { if (entities_.find(id) != entities_.end()) { throw std::runtime_error("Entity with id '" + id + "' already exists in the RO-Crate."); } - - // Add the assigned ID to the Entity itself + + // Construct the entity and assign it the given ID + Entity entity(std::move(types)); entity.assignId(id); - // Add an entity to the RO-Crate's entity register - entities_.emplace(id, entity); + // Add the entity to the RO-Crate's entity register and return a reference to it + entities_.emplace(id, std::move(entity)); + return entities_.at(id); + } + + inline bool ROCrate::hasEntity(const std::string& id) { + return entities_.find(id) != entities_.end(); } inline Entity& ROCrate::getEntity(const std::string& id) { @@ -284,8 +377,25 @@ namespace rocrate { return it->second; } + inline EntityRegister ROCrate::getEntities() const { + return entities_; + } + + inline void ROCrate::addContext(const std::string& value) { + if (value.empty()) { + throw std::invalid_argument("Context value cannot be empty."); + } + + // Ignore if duplicate context value is already present + if (std::find(remoteContext_.begin(), remoteContext_.end(), value) != remoteContext_.end()) { + return; // Context value already exists, do not add it again + } + + // Add the context entry to the RO-Crate's root metadata entity + remoteContext_.push_back(value); + } + inline void ROCrate::addContext(const std::string& key, const std::string& value) { - // Validate the context if (key.empty()) { throw std::invalid_argument("Context key cannot be empty."); } @@ -297,17 +407,33 @@ namespace rocrate { context_[key] = value; } + inline std::vector ROCrate::getRemoteContext() const { + return remoteContext_; + } + + inline std::map ROCrate::getContext() const { + return context_; + } + inline void ROCrate::writeOut(const std::string& path) { // Create the JSON representation of the RO-Crate nlohmann::json outCrate = { - {"@context", "https://w3id.org/ro/crate/1.3/context"}, {"@graph", nlohmann::json::array()} }; // Add the context entries to the JSON representation - if (!context_.empty()) { - outCrate["@context"] = nlohmann::json::array(); - outCrate["@context"].push_back("https://w3id.org/ro/crate/1.3/context"); + if (!remoteContext_.empty() || !context_.empty()) { + // Remote contexts: bare string if only one, array if multiple + if (remoteContext_.size() == 1 && context_.empty()) { + outCrate["@context"] = remoteContext_[0]; + } else { + outCrate["@context"] = nlohmann::json::array(); + for (const auto& remote : remoteContext_) { + outCrate["@context"].push_back(remote); + } + } + + // Local contexts for (const auto& [key, value] : context_) { outCrate["@context"].push_back({{key, value}}); } @@ -352,6 +478,10 @@ namespace rocrate { for (const auto& [key, value] : contextEntry.items()) { addContext(key, value.get()); } + } else if (contextEntry.is_string()) { + addContext(contextEntry.get()); + } else { + throw std::runtime_error("Invalid context entry in RO-Crate JSON: " + contextEntry.dump()); } } } @@ -373,17 +503,13 @@ namespace rocrate { entityTypes.push_back(type.get()); } - // Try getting the entity from the register, if it exists, otherwise create a new one - Entity entity({"Thing"}); // Default type, will be overridden if entity exists - try { - // Existing entity - entity = getEntity(entityId); - updateProperties(entity, entityJson); - } catch (const std::runtime_error&) { - // Entity does not exist, create a new one - entity = Entity(entityTypes); + // Get the entity from the register if it already exists, otherwise create a new one + auto it = entities_.find(entityId); + if (it != entities_.end()) { + updateProperties(it->second, entityJson); + } else { + Entity& entity = createEntity(entityId, entityTypes); updateProperties(entity, entityJson); - addEntity(entityId, entity); } } } @@ -446,7 +572,7 @@ namespace rocrate { nlohmann::json serialized; serialized["@id"] = id; - for (const auto& [property, values] : *entity.properties_) { + for (const auto& [property, values] : entity.properties_) { if (property == "@id") { continue; } diff --git a/tests/example.cpp b/tests/example.cpp index f59c820..2e5fc63 100644 --- a/tests/example.cpp +++ b/tests/example.cpp @@ -17,40 +17,36 @@ void create_example_ro_crate() { // this is currently missing // Get the root metadata entity from the crate and set the description - Entity root = crate.getEntity("ro-crate-metadata.json"); + Entity& root = crate.getEntity("ro-crate-metadata.json"); root.set("description", "RO-Crate Metadata File Descriptor (this file)"); // Add name, description to the root data entity (./) - Entity rootData = crate.getEntity("./"); + Entity& rootData = crate.getEntity("./"); rootData.set("name", "Example RO-Crate"); rootData.set("description", "The RO-Crate Root Data Entity"); // -------------------------------------------------------------------------- // Create the person, which is a contextual entity, and add it to the crate - - Entity alice({"Person"}); + + Entity& alice = crate.createEntity("#alice", {"Person"}); alice.set("name", "Alice"); alice.set("description", "One of hopefully many Contextual Entities"); - crate.addEntity("#alice", alice); // -------------------------------------------------------------------------- // Create the place, another contextual entity, and add it to the crate - Entity catalinaPark({"Place"}); + Entity& catalinaPark = crate.createEntity("http://sws.geonames.org/8152662/", {"Place"}); catalinaPark.set("name", "Catalina Park"); - crate.addEntity("http://sws.geonames.org/8152662/", catalinaPark); // -------------------------------------------------------------------------- // Create two datasets, which are data entities, and add them to the crate. - Entity data1({"File"}); + Entity& data1 = crate.createEntity("data1.txt", {"File"}); data1.set("description", "One of hopefully many Data Entities"); data1.set("author", alice); data1.set("contentLocation", catalinaPark); - crate.addEntity("data1.txt", data1); rootData.set("hasPart", data1); // Ensure that the root data entity has a hasPart relationship to data1 - Entity data2({"File"}); - crate.addEntity("data2.txt", data2); - rootData.set("hasPart", data2); + Entity& data2 = crate.createEntity("data2.txt", {"File"}); + rootData.set("hasPart", data2); // -------------------------------------------------------------------------- // Write out diff --git a/tests/fixtures/add-context.json b/tests/fixtures/add-context.json new file mode 100644 index 0000000..2cd60e1 --- /dev/null +++ b/tests/fixtures/add-context.json @@ -0,0 +1,25 @@ +{ + "@context": [ + "https://w3id.org/ro/crate/1.3/context", + "https://example.com/context2.jsonld", + { + "example": "https://example.com/context.jsonld" + } + ], + "@graph": [ + { + "@id": "./", + "@type": "Dataset" + }, + { + "@id": "ro-crate-metadata.json", + "@type": "CreativeWork", + "about": { + "@id": "./" + }, + "conformsTo": { + "@id": "https://w3id.org/ro/crate/1.3" + } + } + ] +} diff --git a/tests/integration.cpp b/tests/integration.cpp index 9b7a599..2ab4f34 100644 --- a/tests/integration.cpp +++ b/tests/integration.cpp @@ -14,7 +14,7 @@ TEST_CASE("Minimal RO-Crate", "[integration]") ROCrate crate; // Add metadata to root data entity - Entity rootData = crate.getEntity("./"); + Entity& rootData = crate.getEntity("./"); rootData.set("cite-as", "https://doi.org/10.4225/59/59672c09f4a4b"); rootData.set("datePublished", "2017"); rootData.set("name", "Data files associated with the manuscript:Effects of facilitated family case conferencing for ..."); @@ -22,19 +22,16 @@ TEST_CASE("Minimal RO-Crate", "[integration]") rootData.set("creditText", "Agar, M. et al., 2017. Data supporting \"Effects of facilitated family case conferencing for advanced dementia: A cluster randomised clinical trial\". https://doi.org/10.4225/59/59672c09f4a4b"); // Create the license entity - Entity license({"CreativeWork"}); + Entity& license = crate.createEntity("https://creativecommons.org/licenses/by-nc-sa/3.0/au/", {"CreativeWork"}); license.set("description", "This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Australia License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/au/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA."); license.set("identifier", "https://creativecommons.org/licenses/by-nc-sa/3.0/au/"); license.set("name", "Attribution-NonCommercial-ShareAlike 3.0 Australia (CC BY-NC-SA 3.0 AU)"); - crate.addEntity("https://creativecommons.org/licenses/by-nc-sa/3.0/au/", license); - // Create the DOI entry - Entity doi({"PropertyValue"}); + Entity& doi = crate.createEntity("https://doi.org/10.4225/59/59672c09f4a4b", {"PropertyValue"}); doi.set("propertyID", "https://registry.identifiers.org/registry/doi"); doi.set("value", "doi:10.4225/59/59672c09f4a4b"); doi.set("url", "https://doi.org/10.4225/59/59672c09f4a4b"); - crate.addEntity("https://doi.org/10.4225/59/59672c09f4a4b", doi); rootData.set("identifier", doi); // Add license to root data entity @@ -59,31 +56,27 @@ TEST_CASE("Example with file and directory", "[integration]") ROCrate crate; // Add metadata to root data entity - Entity rootData = crate.getEntity("./"); + Entity& rootData = crate.getEntity("./"); rootData.set("name", "Example Dataset"); rootData.set("datePublished", "2016-02-01"); rootData.set("license", "CC-BY"); // Create the author entity - Entity author({"Person"}); + Entity& author = crate.createEntity("https://orcid.org/0000-0003-4953-0830", {"Person"}); author.set("name", "Michael Lake"); - crate.addEntity("https://orcid.org/0000-0003-4953-0830", author); rootData.set("author", author); // Create the file entity - Entity file({"File"}); + Entity& file = crate.createEntity("cp7glop.ai", {"File"}); file.set("name", "Diagram showing trend to increase"); file.set("contentSize", "383766"); file.set("description", "Illustrator file for Glop Pot"); file.set("encodingFormat", "application/pdf"); - crate.addEntity("cp7glop.ai", file); // Create the directory entity - Entity directory({"Dataset"}); + Entity& directory = crate.createEntity("lots_of_little_files/", {"Dataset"}); directory.set("name", "Too many files"); directory.set("description", "This directory contains many small files -- the name of the file is a date in YYYY-MM-DD.csv, each file contains daily temperature readings, sampled hourly for the Glop Pot cave."); - - crate.addEntity("lots_of_little_files/", directory); // Add file and directory to root data entity rootData.set("hasPart", file); @@ -99,7 +92,7 @@ TEST_CASE("Example with file and directory", "[integration]") "/tests/fixtures/example-with-file-directory.json", outputPath ); - + } // REF: https://www.researchobject.org/ro-crate/specification/1.3/data-entities.html#web-based-data-entities @@ -109,22 +102,20 @@ TEST_CASE("Example with web resources", "[integration]") ROCrate crate; // Survey responses file - Entity surveyResponses({"File"}); + Entity& surveyResponses = crate.createEntity("survey-responses-2019.csv", {"File"}); surveyResponses.set("name", "Survey responses"); surveyResponses.set("contentSize", "26452"); surveyResponses.set("encodingFormat", "text/csv"); - crate.addEntity("survey-responses-2019.csv", surveyResponses); // RO-Crate specification file - Entity roCrateSpec({"File"}); + Entity& roCrateSpec = crate.createEntity("https://zenodo.org/record/3541888/files/ro-crate-1.0.0.pdf", {"File"}); roCrateSpec.set("name", "RO-Crate specification"); roCrateSpec.set("contentSize", "310691"); roCrateSpec.set("description", "RO-Crate specification"); roCrateSpec.set("encodingFormat", "application/pdf"); - crate.addEntity("https://zenodo.org/record/3541888/files/ro-crate-1.0.0.pdf", roCrateSpec); // Add to root data entity - Entity rootData = crate.getEntity("./"); + Entity& rootData = crate.getEntity("./"); rootData.set("hasPart", surveyResponses); rootData.set("hasPart", roCrateSpec); @@ -138,7 +129,7 @@ TEST_CASE("Example with web resources", "[integration]") "/tests/fixtures/example-with-web-resources.json", outputPath ); - + } // REF: https://www.researchobject.org/ro-crate/specification/1.3/crate-focus.html (RO-Crates which focus on multiple Contextual Entities) @@ -148,34 +139,32 @@ TEST_CASE("RO-Crate which focuses on multiple Contextual Entities", "[integratio ROCrate crate; // Add metadata to the RO-Crate metadata file descriptor - Entity metadataFileDescriptor = crate.getEntity("ro-crate-metadata.json"); + Entity& metadataFileDescriptor = crate.getEntity("ro-crate-metadata.json"); metadataFileDescriptor.set("description", "RO-Crate Metadata File Descriptor (this file)"); // Add metadata to root data entity - Entity rootData = crate.getEntity("./"); + Entity& rootData = crate.getEntity("./"); rootData.set("name", "Language Data Ontology"); rootData.set("description", "This is an experimental language data ontology based on OLAC terms for use in the ATAP and LDaCA projects"); - + // Add additional context crate.addContext("txc", "https://purl.archive.org/language-data-commons/terms#"); // Create the first contextual entity - Entity annotation({"rdfs:Class"}); + Entity& annotation = crate.createEntity("txc:Annotation", {"rdfs:Class"}); annotation.set("name", "Annotation"); annotation.set("sameAs", "http://www.language-archives.org/REC/type-20020628.html#annotation"); annotation.set("rdfs:comment", "The resource includes information which annotates some other linguistic record."); annotation.set("rdfs:label", "Annotation"); annotation.set("rdfs:subClassOf", "schema:CreativeWork", ValueType::Reference); - crate.addEntity("txc:Annotation", annotation); // Create the second contextual entity - Entity collectionEvent({"rdfs:Class"}); + Entity& collectionEvent = crate.createEntity("txc:CollectionEvent", {"rdfs:Class"}); collectionEvent.set("name", "CollectionEvent"); collectionEvent.set("rdfs:comment", "A description of an event at which one or more PrimaryTexts were captured, e.g. as video or audio"); collectionEvent.set("rdfs:label", "CollectionEvent"); collectionEvent.set("rdfs:subClassOf", "schema:Event", ValueType::Reference); collectionEvent.set("rdfs:subClassOf", "schema:CreateAction", ValueType::Reference); - crate.addEntity("txc:CollectionEvent", collectionEvent); // Add mentions to root data entity rootData.set("mentions", annotation); diff --git a/tests/unit.cpp b/tests/unit.cpp index 7e8e1ff..029cdfc 100644 --- a/tests/unit.cpp +++ b/tests/unit.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include @@ -7,57 +9,97 @@ #include "test_helpers.hpp" using rocrate::Entity; +using rocrate::ROCrate; // ------------------------------------------------------------------------------ // Unit tests for Entity class // ------------------------------------------------------------------------------ TEST_CASE("Ensure entity creation occurs without throwing", "[unit]") { - Entity alice({"Person"}); + ROCrate crate; + crate.createEntity("#alice", {"Person"}); } TEST_CASE("Ensure entity creation throws if no types are provided", "[unit]") { - // Create an entity with an empty types vector, which should throw an invalid_argument exception - REQUIRE_THROWS_AS(Entity(std::vector{}), std::invalid_argument); + // Adding an entity with an empty types vector should throw an invalid_argument exception + ROCrate crate; + REQUIRE_THROWS_AS(crate.createEntity("#thing", std::vector{}), std::invalid_argument); } +TEST_CASE("Ensure set by map succeeds with valid input", "[unit]") { + ROCrate crate; + Entity& alice = crate.createEntity("#alice", {"Person"}); + std::map properties = { + {"name", "Alice"}, + {"description", "One of hopefully many Contextual Entities"} + }; + REQUIRE_NOTHROW(alice.set(properties)); +} + +TEST_CASE("Rejects empty property names in map", "[unit]") { + ROCrate crate; + Entity& entity = crate.createEntity("#thing", {"Thing"}); + std::map properties = { + {"name", "value"}, + {"", "value"} // Invalid property name + }; + + REQUIRE_THROWS_AS(entity.set(properties), std::invalid_argument); +} + +TEST_CASE("Ensure atomic set by map fails if any property is invalid", "[unit]") { + ROCrate crate; + Entity& entity = crate.createEntity("#thing", {"Thing"}); + std::map properties = { + {"name", "value"}, + {"", "value"} // Invalid — should abort the whole call + }; + + REQUIRE_THROWS_AS(entity.set(properties), std::invalid_argument); + REQUIRE_FALSE(entity.getProperties().contains("name")); +} + TEST_CASE("Ensure set by value succeeds with valid input", "[unit]") { - Entity alice({"Person"}); + ROCrate crate; + Entity& alice = crate.createEntity("#alice", {"Person"}); REQUIRE_NOTHROW(alice.set("name", "Alice")); REQUIRE_NOTHROW(alice.set("description", "One of hopefully many Contextual Entities")); } TEST_CASE("Rejects empty property names", "[unit]") { - Entity entity({"Thing"}); + ROCrate crate; + Entity& entity = crate.createEntity("#thing", {"Thing"}); REQUIRE_THROWS_AS(entity.set("", "value"), std::invalid_argument); } TEST_CASE("Rejects empty property values", "[unit]") { - Entity entity({"Thing"}); + ROCrate crate; + Entity& entity = crate.createEntity("#thing", {"Thing"}); REQUIRE_THROWS_AS(entity.set("name", ""), std::invalid_argument); } TEST_CASE("Rejects direct ID assignment", "[unit]") { - Entity entity({"Thing"}); + ROCrate crate; + Entity& entity = crate.createEntity("#thing", {"Thing"}); REQUIRE_THROWS_AS(entity.set("@id", "#thing"), std::invalid_argument); } TEST_CASE("Rejects empty entity IDs", "[unit]") { - rocrate::ROCrate crate; - Entity entity({"Thing"}); + ROCrate crate; REQUIRE_THROWS_AS( - crate.addEntity("", entity), + crate.createEntity("", {"Thing"}), std::invalid_argument ); } TEST_CASE("Rejects empty link property names", "[unit]") { - Entity source({"Thing"}); - Entity target({"Thing"}); + ROCrate crate; + Entity& source = crate.createEntity("#source", {"Thing"}); + Entity& target = crate.createEntity("#target", {"Thing"}); REQUIRE_THROWS_AS( target.set("", source), @@ -66,31 +108,45 @@ TEST_CASE("Rejects empty link property names", "[unit]") { } TEST_CASE("Ignore duplicate key-value pairs", "[unit]") { - Entity entity({"Thing"}); + ROCrate crate; + Entity& entity = crate.createEntity("#thing", {"Thing"}); REQUIRE_NOTHROW(entity.set("name", "value")); REQUIRE_NOTHROW(entity.set("name", "value")); // Should not throw, but also not add a duplicate - SUCCEED("No exceptions thrown, can't currently assert on entity values as they are not exposed in the API"); + REQUIRE(entity.getProperties().at("name").size() == 1); // Should only have one "name" property } -TEST_CASE("Ensure failure if entity is linked before being assigned an ID", "[unit]") { - // Create the person, but do not add to a crate (so no @id yet) - Entity alice({"Person"}); - alice.set("name", "Alice"); - alice.set("description", "One of hopefully many Contextual Entities"); +// ------------------------------------------------------------------------------- +// Unit tests for RO-Crate class +// ------------------------------------------------------------------------------- - // Create a dataset and attempt to link to the person - Entity data1({"File"}); - data1.set("description", "One of hopefully many Data Entities"); +TEST_CASE("ROCrate with a custom root data entity id produces a detached crate", "[unit]") { + rocrate::ROCrate crate("https://example.org/datasets/123"); - // This fails at link time because the linked entity has no @id yet. - REQUIRE_THROWS_AS(data1.set("author", alice), std::runtime_error); + REQUIRE(crate.hasEntity("https://example.org/datasets/123")); + REQUIRE_FALSE(crate.hasEntity("./")); + REQUIRE(crate.hasEntity("ro-crate-metadata.json")); } -// ------------------------------------------------------------------------------- -// Unit tests for RO-Crate class -// ------------------------------------------------------------------------------- +TEST_CASE("Detached RO-Crate's metadata descriptor links to the custom root data entity", "[unit]") { + rocrate::ROCrate crate("https://example.org/datasets/123"); + + const auto properties = crate.getEntity("ro-crate-metadata.json").getProperties(); + REQUIRE(properties.at("about").front().value == "https://example.org/datasets/123"); +} + +TEST_CASE("Standard RO-Crate produced if no rood data entity id provided", "[unit]") { + rocrate::ROCrate crate; + + REQUIRE(crate.hasEntity("./")); +} + +TEST_CASE("hasEntity returns true/false correctly", "[unit]") { + rocrate::ROCrate crate; + REQUIRE(crate.hasEntity("./")); + REQUIRE_FALSE(crate.hasEntity("#nonexistent")); +} TEST_CASE("Get entity throws if entity not found", "[unit]") { // Create a crate @@ -100,6 +156,15 @@ TEST_CASE("Get entity throws if entity not found", "[unit]") { REQUIRE_THROWS_AS(crate.getEntity("#bob"), std::runtime_error); } +TEST_CASE("getEntities get a valid list of entities", "[unit]") { + rocrate::ROCrate crate; + crate.createEntity("#alice", {"Person"}); + crate.createEntity("#bob", {"Person"}); + + rocrate::EntityRegister entities = crate.getEntities(); + REQUIRE(entities.size() == 4); // 2 added + 2 default (root metadata and dataset) +} + TEST_CASE("RO-Crate initilises with valid root metadata and dataset entities", "[unit]") { // Create a crate rocrate::ROCrate crate; @@ -111,13 +176,11 @@ TEST_CASE("RO-Crate initilises with valid root metadata and dataset entities", " REQUIRE_NOTHROW(crate.getEntity("./")); } -TEST_CASE("Crate and builder observe shared entity updates", "[unit]") { +TEST_CASE("createEntity returns a mutable reference into the crate", "[unit]") { rocrate::ROCrate crate; - Entity alice({"Person"}); + Entity& alice = crate.createEntity("#alice", {"Person"}); - crate.addEntity("#alice", alice); - - alice.set("name", "Alice"); + alice.set("name", "Alice"); crate.getEntity("#alice").set("description", "Updated"); SUCCEED("No exceptions thrown, can't currently assert on entity values as they are not exposed in the API"); @@ -137,43 +200,103 @@ TEST_CASE("Duplicate context doesn't throw", "[unit]") { } -TEST_CASE("Add context throws if context is empty", "[unit]") { +TEST_CASE("Add context throws if context value is empty", "[unit]") { + rocrate::ROCrate crate; + REQUIRE_THROWS_AS(crate.addContext("example", ""), std::invalid_argument); +} + +TEST_CASE("Add context with and without prefix (key) yields correct JSON-LD output", "[unit]") { rocrate::ROCrate crate; - REQUIRE_THROWS_AS( - crate.addContext("", "https://example.com/context.jsonld"), - std::invalid_argument + // Add context with prefix + crate.addContext("example", "https://example.com/context.jsonld"); + + // Add context without prefix + crate.addContext("https://example.com/context2.jsonld"); + + // Check that the context has been added correctly + const auto& context = crate.getContext(); + REQUIRE(context.size() == 1); + REQUIRE(context.contains("example")); + + // Check that remote (without prefix) context is present + const auto& remoteContext = crate.getRemoteContext(); + REQUIRE_THAT( + crate.getRemoteContext(), + Catch::Matchers::UnorderedEquals(std::vector{ + "https://w3id.org/ro/crate/1.3/context", + "https://example.com/context2.jsonld" + }) + ); + + // Roundtrip the crate to JSON-LD and back to ensure the contexts are preserved + const std::string outputPath = + std::string(TEST_SOURCE_DIR) + "/add-context.out.json"; + crate.writeOut(outputPath); + + REQUIRE_RO_CRATE_FILE_EQUAL_BY_ID( + std::string(TEST_SOURCE_DIR) + "/tests/fixtures/add-context.json", + outputPath + ); + + // Read the crate back in and check that the contexts are still present + rocrate::ROCrate crate2; + REQUIRE_NOTHROW(crate2.readIn(outputPath)); + crate2.writeOut(outputPath + ".roundtrip.json"); + + REQUIRE_RO_CRATE_FILE_EQUAL_BY_ID( + std::string(TEST_SOURCE_DIR) + "/tests/fixtures/add-context.json", + outputPath + ".roundtrip.json" + ); +} + +TEST_CASE("getContext returns the correct combined context", "[unit]") { + rocrate::ROCrate crate; + + // Add context with prefix + crate.addContext("example", "https://example.com/context.jsonld"); + + // Add context without prefix + crate.addContext("https://example.com/context2.jsonld"); + + // Get the combined context and check that it contains both entries + const auto& context = crate.getContext(); + REQUIRE(context.size() == 1); + REQUIRE(context.contains("example")); + + // Check that remote (without prefix) context is present + const auto& remoteContext = crate.getRemoteContext(); + REQUIRE_THAT( + crate.getRemoteContext(), + Catch::Matchers::UnorderedEquals(std::vector{ + "https://w3id.org/ro/crate/1.3/context", + "https://example.com/context2.jsonld" + }) ); - REQUIRE_THROWS_AS(crate.addContext("example", ""), std::invalid_argument); } TEST_CASE("Add entity throws if ID is empty", "[unit]") { rocrate::ROCrate crate; - Entity alice({"Person"}); - REQUIRE_THROWS_AS(crate.addEntity("", alice), std::invalid_argument); + REQUIRE_THROWS_AS(crate.createEntity("", {"Person"}), std::invalid_argument); } TEST_CASE("Add entity rejects entities with duplicate IDs", "[unit]") { // Create a crate and add an entity rocrate::ROCrate crate; - Entity alice({"Person"}); + Entity& alice = crate.createEntity("#alice", {"Person"}); alice.set("name", "Alice"); - crate.addEntity("#alice", alice); // Attempt to add another entity with the same ID - Entity aliceDuplicate({"Person"}); - aliceDuplicate.set("name", "Alice Duplicate"); - REQUIRE_THROWS_AS(crate.addEntity("#alice", aliceDuplicate), std::runtime_error); + REQUIRE_THROWS_AS(crate.createEntity("#alice", {"Person"}), std::runtime_error); } TEST_CASE("Write out RO-Crate to JSON-LD without throwing", "[unit]") { rocrate::ROCrate crate; - Entity alice({"Person"}); + Entity& alice = crate.createEntity("#alice", {"Person"}); alice.set("name", "Alice"); - crate.addEntity("#alice", alice); REQUIRE_NOTHROW(crate.writeOut("ro-crate-metadata.json")); }