Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,321 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Chris Toshok (toshok@ximian.com)
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using NUnit.Framework;
using System.ComponentModel;
using System.Collections.Generic;
using System;
using System.Collections;
using MonoTests.System.Collections.Specialized;
namespace MonoTests.System.Collections.ObjectModel {
[TestFixture]
public class ObservableCollectionTest {
public ObservableCollectionTest()
{
}
[Test]
public void Insert()
{
bool reached = false;
ObservableCollection<int> col = new ObservableCollection<int> ();
col.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
reached = true;
Assert.AreEqual (NotifyCollectionChangedAction.Add, e.Action, "INS_1");
Assert.AreEqual (0, e.NewStartingIndex, "INS_2");
Assert.AreEqual (-1, e.OldStartingIndex, "INS_3");
Assert.AreEqual (1, e.NewItems.Count, "INS_4");
Assert.AreEqual (5, (int)e.NewItems [0], "INS_5");
Assert.AreEqual (null, e.OldItems, "INS_6");
};
col.Insert (0, 5);
Assert.IsTrue (reached, "INS_5");
}
[Test]
public void RemoveAt()
{
bool reached = false;
ObservableCollection<int> col = new ObservableCollection<int> ();
col.Insert (0, 5);
col.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
reached = true;
Assert.AreEqual (NotifyCollectionChangedAction.Remove, e.Action, "REMAT_1");
Assert.AreEqual (-1, e.NewStartingIndex, "REMAT_2");
Assert.AreEqual (0, e.OldStartingIndex, "REMAT_3");
Assert.AreEqual (null, e.NewItems, "REMAT_4");
Assert.AreEqual (1, e.OldItems.Count, "REMAT_5");
Assert.AreEqual (5, (int)e.OldItems [0], "REMAT_6");
};
col.RemoveAt (0);
Assert.IsTrue (reached, "REMAT_7");
}
[Test]
public void Move()
{
bool reached = false;
ObservableCollection<int> col = new ObservableCollection<int> ();
col.Insert (0, 0);
col.Insert (1, 1);
col.Insert (2, 2);
col.Insert (3, 3);
col.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
reached = true;
Assert.AreEqual (NotifyCollectionChangedAction.Move, e.Action, "MOVE_1");
Assert.AreEqual (3, e.NewStartingIndex, "MOVE_2");
Assert.AreEqual (1, e.OldStartingIndex, "MOVE_3");
Assert.AreEqual (1, e.NewItems.Count, "MOVE_4");
Assert.AreEqual (1, e.NewItems [0], "MOVE_5");
Assert.AreEqual (1, e.OldItems.Count, "MOVE_6");
Assert.AreEqual (1, e.OldItems [0], "MOVE_7");
};
col.Move (1, 3);
Assert.IsTrue (reached, "MOVE_8");
}
[Test]
public void Add()
{
ObservableCollection<char> collection = new ObservableCollection<char> ();
bool propertyChanged = false;
List<string> changedProps = new List<string> ();
NotifyCollectionChangedEventArgs args = null;
((INotifyPropertyChanged)collection).PropertyChanged += delegate (object sender, PropertyChangedEventArgs e) {
propertyChanged = true;
changedProps.Add (e.PropertyName);
};
collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
args = e;
};
collection.Add ('A');
Assert.IsTrue (propertyChanged, "ADD_1");
Assert.IsTrue (changedProps.Contains ("Count"), "ADD_2");
Assert.IsTrue (changedProps.Contains ("Item[]"), "ADD_3");
CollectionChangedEventValidators.ValidateAddOperation (args, new char [] { 'A' }, 0, "ADD_4");
}
[Test]
public void Remove()
{
ObservableCollection<char> collection = new ObservableCollection<char> ();
bool propertyChanged = false;
List<string> changedProps = new List<string> ();
NotifyCollectionChangedEventArgs args = null;
collection.Add ('A');
collection.Add ('B');
collection.Add ('C');
((INotifyPropertyChanged)collection).PropertyChanged += delegate (object sender, PropertyChangedEventArgs e) {
propertyChanged = true;
changedProps.Add (e.PropertyName);
};
collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
args = e;
};
collection.Remove ('B');
Assert.IsTrue (propertyChanged, "REM_1");
Assert.IsTrue (changedProps.Contains ("Count"), "REM_2");
Assert.IsTrue (changedProps.Contains ("Item[]"), "REM_3");
CollectionChangedEventValidators.ValidateRemoveOperation (args, new char [] { 'B' }, 1, "REM_4");
}
[Test]
public void Set()
{
ObservableCollection<char> collection = new ObservableCollection<char> ();
bool propertyChanged = false;
List<string> changedProps = new List<string> ();
NotifyCollectionChangedEventArgs args = null;
collection.Add ('A');
collection.Add ('B');
collection.Add ('C');
((INotifyPropertyChanged)collection).PropertyChanged += delegate (object sender, PropertyChangedEventArgs e) {
propertyChanged = true;
changedProps.Add (e.PropertyName);
};
collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
args = e;
};
collection [2] = 'I';
Assert.IsTrue (propertyChanged, "SET_1");
Assert.IsTrue (changedProps.Contains ("Item[]"), "SET_2");
CollectionChangedEventValidators.ValidateReplaceOperation (args, new char [] { 'C' }, new char [] { 'I' }, 2, "SET_3");
}
[Test]
public void Reentrant()
{
ObservableCollection<char> collection = new ObservableCollection<char> ();
bool propertyChanged = false;
List<string> changedProps = new List<string> ();
NotifyCollectionChangedEventArgs args = null;
collection.Add ('A');
collection.Add ('B');
collection.Add ('C');
PropertyChangedEventHandler pceh = delegate (object sender, PropertyChangedEventArgs e) {
propertyChanged = true;
changedProps.Add (e.PropertyName);
};
// Adding a PropertyChanged event handler
((INotifyPropertyChanged)collection).PropertyChanged += pceh;
collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
args = e;
};
collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
// This one will attempt to break reentrancy
try {
collection.Add ('X');
Assert.Fail ("Reentrancy should not be allowed.");
} catch (InvalidOperationException) {
}
};
collection [2] = 'I';
Assert.IsTrue (propertyChanged, "REENT_1");
Assert.IsTrue (changedProps.Contains ("Item[]"), "REENT_2");
CollectionChangedEventValidators.ValidateReplaceOperation (args, new char [] { 'C' }, new char [] { 'I' }, 2, "REENT_3");
// Removing the PropertyChanged event handler should work as well:
((INotifyPropertyChanged)collection).PropertyChanged -= pceh;
}
//Private test class for protected members of ObservableCollection
private class ObservableCollectionTestHelper : ObservableCollection<char> {
internal void DoubleEnterReentrant()
{
IDisposable object1 = BlockReentrancy ();
IDisposable object2 = BlockReentrancy ();
Assert.AreSame (object1, object2);
//With double block, try the reentrant:
NotifyCollectionChangedEventArgs args = null;
CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
args = e;
};
// We need a second callback for reentrancy to matter
CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
// Doesn't need to do anything; just needs more than one callback registered.
};
// Try adding - this should cause reentrancy, and fail
try {
Add ('I');
Assert.Fail ("Reentrancy should not be allowed. -- #2");
} catch (InvalidOperationException) {
}
// Release the first reentrant
object1.Dispose ();
// Try adding again - this should cause reentrancy, and fail again
try {
Add ('J');
Assert.Fail ("Reentrancy should not be allowed. -- #3");
} catch (InvalidOperationException) {
}
// Release the reentrant a second time
object1.Dispose ();
// This last add should work fine.
Add ('K');
CollectionChangedEventValidators.ValidateAddOperation (args, new char [] { 'K' }, 0, "REENTHELP_1");
}
}
[Test]
public void ReentrantReuseObject()
{
ObservableCollectionTestHelper helper = new ObservableCollectionTestHelper ();
helper.DoubleEnterReentrant ();
}
[Test]
public void Clear()
{
List<char> initial = new List<char> ();
initial.Add ('A');
initial.Add ('B');
initial.Add ('C');
ObservableCollection<char> collection = new ObservableCollection<char> (initial);
bool propertyChanged = false;
List<string> changedProps = new List<string> ();
NotifyCollectionChangedEventArgs args = null;
((INotifyPropertyChanged)collection).PropertyChanged += delegate (object sender, PropertyChangedEventArgs e) {
propertyChanged = true;
changedProps.Add (e.PropertyName);
};
collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
args = e;
};
collection.Clear ();
Assert.IsTrue (propertyChanged, "CLEAR_1");
Assert.IsTrue (changedProps.Contains ("Count"), "CLEAR_2");
Assert.IsTrue (changedProps.Contains ("Item[]"), "CLEAR_3");
CollectionChangedEventValidators.ValidateResetOperation (args, "CLEAR_4");
}
}
}

View File

@@ -0,0 +1,92 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Authors:
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using MonoTests.System.Collections.Specialized;
using NUnit.Framework;
namespace MonoTests.System.Collections.ObjectModel {
[TestFixture]
public class ReadOnlyObservableCollectionTest {
[Test]
public void ClassTest()
{
// Because the collection cannot change, check to make sure exceptions are thrown for modifications.
List<char> initial = new List<char> ();
initial.Add ('A');
initial.Add ('B');
initial.Add ('C');
ObservableCollection<char> collection = new ObservableCollection<char> (initial);
ReadOnlyObservableCollection<char> readOnlyCollection = new ReadOnlyObservableCollection<char> (collection);
// Test the events
PropertyChangedEventHandler pceh = delegate (object sender, PropertyChangedEventArgs e) {
Assert.Fail ("No properties should change.");
};
NotifyCollectionChangedEventHandler ncceh = delegate (object sender, NotifyCollectionChangedEventArgs e) {
Assert.Fail ("The collection should not change.");
};
((INotifyPropertyChanged)readOnlyCollection).PropertyChanged += pceh;
((INotifyCollectionChanged)readOnlyCollection).CollectionChanged += ncceh;
// Done with the events.
((INotifyPropertyChanged)readOnlyCollection).PropertyChanged -= pceh;
((INotifyCollectionChanged)readOnlyCollection).CollectionChanged -= ncceh;
Assert.AreEqual (3, readOnlyCollection.Count, "RO_1");
CollectionChangedEventValidators.AssertEquivalentLists (initial, readOnlyCollection, "RO_2");
// Modifying the underlying collection
bool propChanged = false;
pceh = delegate (object sender, PropertyChangedEventArgs e) {
propChanged = true;
};
ncceh = delegate (object sender, NotifyCollectionChangedEventArgs e) {
CollectionChangedEventValidators.ValidateAddOperation (e, new char [] { 'I' }, 3, "RO_3");
};
((INotifyPropertyChanged)readOnlyCollection).PropertyChanged += pceh;
((INotifyCollectionChanged)readOnlyCollection).CollectionChanged += ncceh;
// In theory, this will cause the properties to change.
collection.Add ('I');
Assert.IsTrue (propChanged, "RO_4");
}
}
}

View File

@@ -0,0 +1,102 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Authors:
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System.Collections;
using NUnit.Framework;
using System.Collections.Specialized;
namespace MonoTests.System.Collections.Specialized {
internal static class CollectionChangedEventValidators {
#region Validators
internal static void AssertEquivalentLists(IList expected, IList actual, string message)
{
if (expected == null) {
Assert.IsNull (actual, "LISTEQ_1A::" + message);
return;
} else
Assert.IsNotNull (actual, "LISTEQ_1B::" + message);
Assert.AreEqual (expected.Count, actual.Count, "LISTEQ_2::" + message);
for (int i = 0; i < expected.Count; i++)
Assert.AreEqual (expected [i], actual [i], "LISTEQ_3::" + message);
}
private static void ValidateCommon(NotifyCollectionChangedEventArgs args, NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newIndex, int oldIndex, string message)
{
Assert.IsNotNull (args, "NCCVAL_1::" + message);
Assert.AreEqual (action, args.Action, "NCCVAL_2::" + message);
AssertEquivalentLists (newItems, args.NewItems, "NCCVAL_3::" + message);
AssertEquivalentLists (oldItems, args.OldItems, "NCCVAL_4::" + message);
Assert.AreEqual (newIndex, args.NewStartingIndex, "NCCVAL_5::" + message);
Assert.AreEqual (oldIndex, args.OldStartingIndex, "NCCVAL_6::" + message);
}
internal static void ValidateResetOperation(NotifyCollectionChangedEventArgs args, string message)
{
ValidateCommon (args, NotifyCollectionChangedAction.Reset, null, null, -1, -1, message);
}
internal static void ValidateAddOperation(NotifyCollectionChangedEventArgs args, IList newItems, string message)
{
ValidateAddOperation (args, newItems, -1, message);
}
internal static void ValidateAddOperation(NotifyCollectionChangedEventArgs args, IList newItems, int startIndex, string message)
{
ValidateCommon (args, NotifyCollectionChangedAction.Add, newItems, null, startIndex, -1, message);
}
internal static void ValidateRemoveOperation(NotifyCollectionChangedEventArgs args, IList oldItems, string message)
{
ValidateRemoveOperation (args, oldItems, -1, message);
}
internal static void ValidateRemoveOperation(NotifyCollectionChangedEventArgs args, IList oldItems, int startIndex, string message)
{
ValidateCommon (args, NotifyCollectionChangedAction.Remove, null, oldItems, -1, startIndex, message);
}
internal static void ValidateReplaceOperation(NotifyCollectionChangedEventArgs args, IList oldItems, IList newItems, string message)
{
ValidateReplaceOperation (args, oldItems, newItems, -1, message);
}
internal static void ValidateReplaceOperation(NotifyCollectionChangedEventArgs args, IList oldItems, IList newItems, int startIndex, string message)
{
ValidateCommon (args, NotifyCollectionChangedAction.Replace, newItems, oldItems, startIndex, startIndex, message);
}
internal static void ValidateMoveOperation(NotifyCollectionChangedEventArgs args, IList changedItems, int newIndex, int oldIndex, string message)
{
ValidateCommon (args, NotifyCollectionChangedAction.Move, changedItems, changedItems, newIndex, oldIndex, message);
}
#endregion
}
}

View File

@@ -0,0 +1,78 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System;
using NUnit.Framework;
using System.ComponentModel;
namespace MonoTests.System.ComponentModel {
[TestFixture]
public class CurrentChangingEventArgsTest {
public CurrentChangingEventArgsTest()
{
}
[Test]
public void CurrentChangingEventArgsConstructor1Test()
{
CurrentChangingEventArgs args = new CurrentChangingEventArgs ();
Assert.IsFalse (args.Cancel, "CTOR1_#1");
Assert.IsTrue (args.IsCancelable, "CTOR1_#2");
}
[Test]
public void CurrentChangingEventArgsConstructor2Test()
{
CurrentChangingEventArgs args = new CurrentChangingEventArgs (false);
Assert.IsFalse (args.Cancel, "CTOR2_#1");
Assert.IsFalse (args.IsCancelable, "CTOR2_#2");
args = new CurrentChangingEventArgs (true);
Assert.IsFalse (args.Cancel, "CTOR1_#3");
Assert.IsTrue (args.IsCancelable, "CTOR1_#4");
args.Cancel = true;
Assert.IsTrue (args.Cancel, "CTOR1_#5");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ChangeCancelIfNotCancelableTest()
{
CurrentChangingEventArgs args = new CurrentChangingEventArgs (false);
Assert.IsFalse (args.Cancel, "InvOp_#1");
Assert.IsFalse (args.IsCancelable, "InvOp_#2");
args.Cancel = true;
}
}
}

View File

@@ -0,0 +1,68 @@
//
// GroupDescriptionTest.cs
//
// Author:
// Antonius Riha <antoniusriha@gmail.com>
//
// Copyright (c) 2014 Antonius Riha
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Globalization;
using NUnit.Framework;
namespace MonoTests.System.ComponentModel
{
[TestFixture]
public class GroupDescriptionTest
{
[Test]
public void NamesMatch ()
{
var gd = new ConcreteGroupDescription ();
var obj = new object ();
Assert.IsTrue (gd.NamesMatch (obj, obj), "A1");
Assert.IsFalse (gd.NamesMatch (new object (), new object ()), "A2");
}
[Test]
public void ShouldSerializeGroupNames ()
{
var g = new ConcreteGroupDescription ();
g.GroupNames.Add ("name");
Assert.IsTrue (g.ShouldSerializeGroupNames (), "#A1");
}
[Test]
public void ShouldSerializeGroupNamesEmpty ()
{
var g = new ConcreteGroupDescription ();
Assert.IsFalse (g.ShouldSerializeGroupNames (), "#A1");
}
class ConcreteGroupDescription : GroupDescription
{
public override object GroupNameFromItem (object item, int level, CultureInfo culture)
{
throw new NotSupportedException ();
}
}
}
}

View File

@@ -0,0 +1,287 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.ComponentModel;
namespace MonoTests.System.ComponentModel
{
[TestFixture]
public class PropertyFilterAttributeTest
{
public PropertyFilterAttributeTest()
{
}
[Test]
public void PropertyFilterAttributeFilterTest()
{
Assert.AreEqual (PropertyFilterOptions.All, PropertyFilterAttribute.Default.Filter, "Filter_#1");
Assert.AreEqual (PropertyFilterOptions.None, new PropertyFilterAttribute(PropertyFilterOptions.None).Filter, "Filter_#2");
Assert.AreEqual (PropertyFilterOptions.SetValues, new PropertyFilterAttribute (PropertyFilterOptions.SetValues).Filter, "Filter_#3");
Assert.AreEqual (PropertyFilterOptions.Valid.GetHashCode(), new PropertyFilterAttribute (PropertyFilterOptions.Valid).GetHashCode(), "Filter_#4");
}
private static PropertyFilterAttribute [] CreateAllAttributeOptions()
{
// This iterates over all possible combinations
PropertyFilterAttribute [] opts = new PropertyFilterAttribute [16];
for (int i = 0; i < 16; i++) {
// Note: This is certainly not an ideal technique for this, but it saves space
opts [i] = new PropertyFilterAttribute ((PropertyFilterOptions)i);
}
return opts;
}
private static readonly PropertyFilterAttribute [] AllAttributeOptions = CreateAllAttributeOptions ();
private static void ValidateFilterValues(PropertyFilterAttribute test, bool[] matchResults, int equalsResult, string message)
{
for (int i = 0; i < 16; i++) {
Assert.AreEqual(matchResults[i], test.Match(AllAttributeOptions[i]),
message + " - Match - Iteration " + i + ": " +
Enum.GetName(typeof(PropertyFilterOptions), (PropertyFilterOptions)i));
Assert.AreEqual (equalsResult == i, test.Equals (AllAttributeOptions [i]),
message + " - Equals - Iteration " + i + ": " +
Enum.GetName (typeof (PropertyFilterOptions), (PropertyFilterOptions)i));
}
}
[Test]
public void PropertyFilterAttributeOptionsNoneTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.None);
bool [] matches = new bool [] {
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
};
ValidateFilterValues (all, matches, (int)PropertyFilterOptions.None, "None");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid);
bool [] matches = new bool [] {
false, true, false, true, false, true, false, true,
false, true, false, true, false, true, false, true,
};
ValidateFilterValues (all, matches, (int)PropertyFilterOptions.Invalid, "Invalid");
}
[Test]
public void PropertyFilterAttributeOptionsSetValuesTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.SetValues);
bool [] matches = new bool [] {
false, false, true, true, false, false, true, true,
false, false, true, true, false, false, true, true,
};
ValidateFilterValues (all, matches, (int)PropertyFilterOptions.SetValues, "SetValues");
}
[Test]
public void PropertyFilterAttributeOptionsUnsetValuesTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.UnsetValues);
bool [] matches = new bool [] {
false, false, false, false, true, true, true, true,
false, false, false, false, true, true, true, true,
};
ValidateFilterValues (all, matches, (int)PropertyFilterOptions.UnsetValues, "UnsetValues");
}
[Test]
public void PropertyFilterAttributeOptionsValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
true, true, true, true, true, true, true, true,
};
ValidateFilterValues (all, matches, (int)PropertyFilterOptions.Valid, "Valid");
}
[Test]
public void PropertyFilterAttributeOptionsAllTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.All);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, true,
};
ValidateFilterValues (all, matches, (int)PropertyFilterOptions.All, "All");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidSetValuesTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid | PropertyFilterOptions.SetValues);
bool [] matches = new bool [] {
false, false, false, true, false, false, false, true,
false, false, false, true, false, false, false, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.Invalid | PropertyFilterOptions.SetValues), "Invalid|SetValues");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidUnsetValuesTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid | PropertyFilterOptions.UnsetValues);
bool [] matches = new bool [] {
false, false, false, false, false, true, false, true,
false, false, false, false, false, true, false, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.Invalid | PropertyFilterOptions.UnsetValues), "Invalid|UnsetValues");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid | PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, true, false, true, false, true, false, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.Invalid | PropertyFilterOptions.Valid), "Invalid|Valid");
}
[Test]
public void PropertyFilterAttributeOptionsSetValuesUnsetValuesTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.SetValues | PropertyFilterOptions.UnsetValues);
bool [] matches = new bool [] {
false, false, false, false, false, false, true, true,
false, false, false, false, false, false, true, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.SetValues | PropertyFilterOptions.UnsetValues), "SetValues|UnsetValues");
}
[Test]
public void PropertyFilterAttributeOptionsSetValuesValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.SetValues | PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, false, true, true, false, false, true, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.SetValues | PropertyFilterOptions.Valid), "SetValues|Valid");
}
[Test]
public void PropertyFilterAttributeOptionsUnsetValuesValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.UnsetValues | PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, false, false, false, true, true, true, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.UnsetValues | PropertyFilterOptions.Valid), "UnsetValues|Valid");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidSetValuesUnsetValuesTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid | PropertyFilterOptions.SetValues | PropertyFilterOptions.UnsetValues);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, true,
false, false, false, false, false, false, false, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.Invalid | PropertyFilterOptions.SetValues | PropertyFilterOptions.UnsetValues), "Invalid|SetValues|UnsetValues");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidSetValuesValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid | PropertyFilterOptions.SetValues | PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, false, false, true, false, false, false, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.Invalid | PropertyFilterOptions.SetValues | PropertyFilterOptions.Valid), "Invalid|SetValues|Valid");
}
[Test]
public void PropertyFilterAttributeOptionsInvalidUnsetValuesValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.Invalid | PropertyFilterOptions.UnsetValues | PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, false, false, false, false, true, false, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.Invalid | PropertyFilterOptions.UnsetValues | PropertyFilterOptions.Valid), "Invalid|UnsetValues|Valid");
}
[Test]
public void PropertyFilterAttributeOptionsSetValuesUnsetValuesValidTest()
{
PropertyFilterAttribute all = new PropertyFilterAttribute (PropertyFilterOptions.SetValues | PropertyFilterOptions.UnsetValues | PropertyFilterOptions.Valid);
bool [] matches = new bool [] {
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, true, true,
};
ValidateFilterValues (all, matches, (int)(PropertyFilterOptions.SetValues | PropertyFilterOptions.UnsetValues | PropertyFilterOptions.Valid), "SetValues|UnsetValues|Valid");
}
}
}

View File

@@ -0,0 +1,202 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.ComponentModel;
using System.Collections.Specialized;
namespace MonoTests.System.ComponentModel {
[TestFixture]
public class SortDescriptionCollectionTest
{
public SortDescriptionCollectionTest()
{
}
[Test]
public void SortDescriptionCollectionAddTest()
{
SortDescriptionCollection sdc = new SortDescriptionCollection ();
SortDescription addedItem = new SortDescription ("NONE", ListSortDirection.Ascending);
((INotifyCollectionChanged)sdc).CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
Assert.AreEqual (NotifyCollectionChangedAction.Add, e.Action, "ADD_#0");
addedItem = (SortDescription)e.NewItems [0];
Assert.AreEqual (true, addedItem.IsSealed, "ADD_#0b");
};
sdc.Add (new SortDescription ("A", ListSortDirection.Ascending));
Assert.AreEqual ("A", addedItem.PropertyName, "ADD_#1");
Assert.AreEqual (ListSortDirection.Ascending, addedItem.Direction, "ADD_#2");
Assert.AreEqual (true, addedItem.IsSealed, "ADD_#3");
}
[Test]
public void SortDescriptionCollectionAddNoHandlerTest()
{
SortDescriptionCollection sdc = new SortDescriptionCollection ();
SortDescription addedItem = new SortDescription ("A", ListSortDirection.Ascending);
sdc.Add (addedItem);
addedItem = sdc[0];
Assert.AreEqual ("A", addedItem.PropertyName, "ADDN_#1");
Assert.AreEqual (ListSortDirection.Ascending, addedItem.Direction, "ADDN_#2");
Assert.AreEqual (true, addedItem.IsSealed, "ADDN_#3");
}
[Test]
public void SortDescriptionCollectionRemoveTest()
{
SortDescriptionCollection sdc = new SortDescriptionCollection ();
SortDescription removedItem = new SortDescription ("NONE", ListSortDirection.Ascending);
sdc.Add (new SortDescription ("A", ListSortDirection.Ascending));
((INotifyCollectionChanged)sdc).CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
Assert.AreEqual (NotifyCollectionChangedAction.Remove, e.Action, "REM_#0");
removedItem = (SortDescription)e.OldItems [0];
Assert.AreEqual (true, removedItem.IsSealed, "REM_#0b");
};
sdc.RemoveAt (0);
Assert.AreEqual ("A", removedItem.PropertyName, "REM_#1");
Assert.AreEqual (ListSortDirection.Ascending, removedItem.Direction, "REM_#2");
Assert.AreEqual (true, removedItem.IsSealed, "REM_#3");
}
[Test]
public void SortDescriptionCollectionClearTest()
{
SortDescriptionCollection sdc = new SortDescriptionCollection ();
bool eventFired = false;
sdc.Add (new SortDescription ("A", ListSortDirection.Ascending));
((INotifyCollectionChanged)sdc).CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
Assert.AreEqual (NotifyCollectionChangedAction.Reset, e.Action, "CLR_#0");
eventFired = true;
};
sdc.Clear ();
Assert.IsTrue (eventFired, "CLR_#1");
}
[Test]
public void SortDescriptionCollectionSetTest()
{
SortDescriptionCollection sdc = new SortDescriptionCollection ();
int addEvent = 0, removeEvent = 0;
SortDescription addedItem = new SortDescription ("NONE", ListSortDirection.Ascending);
SortDescription removedItem = new SortDescription ("NONE", ListSortDirection.Ascending);
sdc.Add (new SortDescription ("A", ListSortDirection.Ascending));
((INotifyCollectionChanged)sdc).CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
addEvent++;
addedItem = (SortDescription)e.NewItems [0];
break;
case NotifyCollectionChangedAction.Remove:
removeEvent++;
removedItem = (SortDescription)e.OldItems [0];
break;
default:
Assert.Fail ("SET_#0");
break;
}
};
sdc [0] = new SortDescription ("B", ListSortDirection.Descending);
Assert.AreEqual (1, addEvent, "SET_#1");
Assert.AreEqual (1, removeEvent, "SET_#2");
Assert.AreEqual ("A", removedItem.PropertyName, "REM_#1");
Assert.AreEqual (ListSortDirection.Ascending, removedItem.Direction, "REM_#2");
Assert.AreEqual (true, removedItem.IsSealed, "REM_#3");
Assert.AreEqual ("B", addedItem.PropertyName, "ADD_#1");
Assert.AreEqual (ListSortDirection.Descending, addedItem.Direction, "ADD_#2");
Assert.AreEqual (true, addedItem.IsSealed, "ADD_#3");
}
[Test]
public void GetEmptyCollection ()
{
var collection = SortDescriptionCollection.Empty;
CollectionAssert.IsEmpty (collection, "A1");
}
[Test]
[ExpectedException (typeof(NotSupportedException))]
public void AddToEmptyCollection ()
{
var collection = SortDescriptionCollection.Empty;
collection.Add (new SortDescription ());
}
[Test]
public void RemoveFromEmptyCollection ()
{
var collection = SortDescriptionCollection.Empty;
Assert.IsFalse (collection.Remove (new SortDescription ()), "A1");
}
[Test]
[ExpectedException (typeof(NotSupportedException))]
public void RemoveAtIndexFromEmptyCollection ()
{
var collection = SortDescriptionCollection.Empty;
collection.RemoveAt (0);
}
[Test]
[ExpectedException (typeof(NotSupportedException))]
public void ClearEmptyCollection ()
{
var collection = SortDescriptionCollection.Empty;
collection.Clear ();
}
[Test]
[ExpectedException (typeof(NotSupportedException))]
public void InsertIntoEmptyCollection ()
{
var collection = SortDescriptionCollection.Empty;
collection.Insert (0, new SortDescription ());
}
}
}

View File

@@ -0,0 +1,176 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Brian O'Keefe (zer0keefie@gmail.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.ComponentModel;
using System.Reflection;
namespace MonoTests.System.ComponentModel
{
[TestFixture]
public class SortDescriptionTest
{
public SortDescriptionTest()
{
}
[Test]
public void ConstructorTest()
{
string propertyName = "SampleProperty";
SortDescription sd = new SortDescription (propertyName, ListSortDirection.Ascending);
Assert.AreEqual (propertyName, sd.PropertyName, "CTOR_#1");
Assert.AreEqual (ListSortDirection.Ascending, sd.Direction, "CTOR_#2");
Assert.IsFalse (sd.IsSealed, "CTOR_#3");
sd = new SortDescription (propertyName, ListSortDirection.Descending);
Assert.AreEqual (ListSortDirection.Descending, sd.Direction, "CTOR_#3");
sd.Direction = ListSortDirection.Ascending;
Assert.AreEqual (ListSortDirection.Ascending, sd.Direction, "CTOR_#4");
sd.PropertyName = "NewProperty";
Assert.AreEqual("NewProperty", sd.PropertyName, "CTOR_#5");
}
[Test]
public void NullArgumentTest() {
SortDescription sd = new SortDescription(null, ListSortDirection.Ascending);
Assert.IsNull(sd.PropertyName, "NullArg_#1");
}
[Test]
public void EmptyArgumentTest() {
SortDescription sd = new SortDescription(string.Empty, ListSortDirection.Ascending);
Assert.AreEqual(string.Empty, sd.PropertyName, "EmptyArg_#1");
}
[Test]
[ExpectedException(typeof(InvalidEnumArgumentException))]
public void InvalidEnumArgumentTest() {
new SortDescription("Test", (ListSortDirection)3);
}
[Test]
public void NullArgumentAssignmentTest() {
SortDescription sd = new SortDescription("Test", ListSortDirection.Ascending);
sd.PropertyName = null;
Assert.IsNull(sd.PropertyName, "AssignNull_#1");
}
[Test]
public void EmptyArgumentAssignmentTest() {
SortDescription sd = new SortDescription("Test", ListSortDirection.Ascending);
sd.PropertyName = string.Empty;
Assert.AreEqual(string.Empty, sd.PropertyName, "AssignEmpty_#1");
}
[Test]
public void OperatorTest()
{
SortDescription left = new SortDescription ("A", ListSortDirection.Ascending);
SortDescription same = new SortDescription ("A", ListSortDirection.Ascending);
SortDescription diffProp = new SortDescription ("B", ListSortDirection.Ascending);
SortDescription diffDir = new SortDescription ("A", ListSortDirection.Descending);
Assert.IsTrue (left == same, "OP_#1");
Assert.IsFalse (left == diffProp, "OP_#2");
Assert.IsFalse (left == diffDir, "OP_#3");
Assert.IsFalse (left == null, "OP_#4");
Assert.IsFalse (left != same, "OP_#5");
Assert.IsTrue (left != diffProp, "OP_#6");
Assert.IsTrue (left != diffDir, "OP_#7");
Assert.IsTrue (left != null, "OP_#8");
Assert.IsTrue (left.Equals (same), "OP_#9");
Assert.IsFalse (left.Equals (diffProp), "OP_#10");
Assert.IsFalse (left.Equals (diffDir), "OP_#11");
Assert.IsFalse (left.Equals (null), "OP_#12");
}
[Test]
public void ToStringAndHashCodeTest()
{
SortDescription sd = new SortDescription ("Sample", ListSortDirection.Ascending);
Assert.AreEqual ("System.ComponentModel.SortDescription", sd.ToString (), "TSHC_#1");
Assert.AreEqual ("Sample".GetHashCode () ^ ListSortDirection.Ascending.GetHashCode(),
sd.GetHashCode (), "TSHC_#2");
sd = new SortDescription ("Sample", ListSortDirection.Descending);
Assert.AreEqual ("Sample".GetHashCode () ^ ListSortDirection.Descending.GetHashCode (),
sd.GetHashCode (), "TSHC_#3");
sd = new SortDescription(null, ListSortDirection.Descending);
Assert.AreEqual (ListSortDirection.Descending.GetHashCode (), sd.GetHashCode( ), "TSHC_#4");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SetSealedPropertyNameTest() {
SortDescription sd = new SortDescription("Test", ListSortDirection.Ascending);
// Need to borrow the add method of SortDescriptionCollection to seal the
// SortDescription (Seal is internal)
SortDescriptionCollection sdc = new SortDescriptionCollection ();
sdc.Add (sd);
sd = sdc [0];
// SD is sealed now.
Assert.IsTrue (sd.IsSealed, "SealedProp_#1");
sd.PropertyName = "NewProperty";
Assert.AreEqual ("NewProperty", sd.PropertyName, "SealedProp_#1");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SetSealedDirectionTest() {
SortDescription sd = new SortDescription ("Test", ListSortDirection.Ascending);
// Need to borrow the add method of SortDescriptionCollection to seal the
// SortDescription (Seal is internal)
SortDescriptionCollection sdc = new SortDescriptionCollection ();
sdc.Add (sd);
sd = sdc [0];
// SD is sealed now.
Assert.IsTrue(sd.IsSealed, "SealedProp_#1");
sd.Direction = ListSortDirection.Descending;
Assert.AreEqual (ListSortDirection.Descending, sd.Direction, "SealedProp_#1");
}
}
}

View File

@@ -0,0 +1,80 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
namespace System.IO.Packaging.Tests {
public class FakePackage : Package {
Dictionary<Uri, PackagePart> Parts { get; set; }
public List<Uri> CreatedParts { get; private set; }
public List<Uri> DeletedParts { get; private set; }
public List<Uri> GotParts { get; private set; }
public FakePackage (FileAccess access, bool streaming)
: base (access, streaming)
{
CreatedParts = new List<Uri> ();
DeletedParts = new List<Uri> ();
GotParts = new List<Uri>();
Parts = new Dictionary<Uri, PackagePart> ();
}
protected override PackagePart CreatePartCore (Uri partUri, string contentType, CompressionOption compressionOption)
{
FakePackagePart p = new FakePackagePart (this, partUri, contentType, compressionOption);
Parts.Add (p.Uri, p);
CreatedParts.Add (partUri);
return p;
}
protected override void DeletePartCore (Uri partUri)
{
DeletedParts.Add (partUri);
Parts.Remove (partUri);
}
protected override void FlushCore ()
{
// Flush...
}
protected override PackagePart GetPartCore (Uri partUri)
{
if (!GotParts.Contains (partUri))
GotParts.Add (partUri);
return Parts.ContainsKey(partUri) ? Parts [partUri] : null;
}
protected override PackagePart [] GetPartsCore ()
{
PackagePart [] p = new PackagePart [Parts.Count];
Parts.Values.CopyTo (p, 0);
return p;
}
}
}

View File

@@ -0,0 +1,67 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
namespace System.IO.Packaging.Tests {
class FakePackagePart : PackagePart {
public List<FileAccess> Accesses { get; private set; }
public List<FileMode> Modes { get; private set; }
public FakePackagePart (Package package, Uri partUri)
: base (package, partUri)
{
Init ();
}
public FakePackagePart (Package package, Uri partUri, string contentType)
: base(package, partUri, contentType)
{
Init ();
}
public FakePackagePart (Package package, Uri partUri, string contentType, CompressionOption compressionOption)
: base (package, partUri, contentType, compressionOption)
{
Init ();
}
private void Init ()
{
Accesses = new List<FileAccess> ();
Modes = new List<FileMode> ();
}
protected override Stream GetStreamCore (FileMode mode, FileAccess access)
{
Accesses.Add (access);
Modes.Add (mode);
return new MemoryStream ();
}
}
}

View File

@@ -0,0 +1,236 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
namespace System.IO.Packaging.Tests {
[TestFixture]
public class FakePackagePartTests : TestBase {
static void Main (string [] args)
{
FakePackagePartTests t = new FakePackagePartTests ();
t.FixtureSetup ();
t.Setup ();
t.GetStream2 ();
}
FakePackagePart part;
public override void Setup ()
{
base.Setup ();
part = (FakePackagePart) new FakePackagePart(package, uris [0], contentType);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor1 ()
{
FakePackagePart p = new FakePackagePart (null, null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor2 ()
{
FakePackagePart p = new FakePackagePart (package, null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor3 ()
{
FakePackagePart p = new FakePackagePart (null, uris [0]);
}
[Test]
public void Constructor4 ()
{
new FakePackagePart (package, uris [0], null);
}
[Test]
public void Constructor5 ()
{
new FakePackagePart (package, uris [0], "");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Constructor6 ()
{
new FakePackagePart (package, uris [0], "dgsdgdfgd");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateRelationship1 ()
{
part.CreateRelationship (null, TargetMode.External, null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateRelationship2 ()
{
part.CreateRelationship (uris [1], TargetMode.External, null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CreateRelationship3a ()
{
part.CreateRelationship (uris [1], TargetMode.External, "");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CreateRelationship3b ()
{
part.CreateRelationship (uris [1], TargetMode.External, " ");
}
[Test]
public void CreateRelationship4 ()
{
part.CreateRelationship (uris [1], TargetMode.External, "blah");
}
[Test]
public void CreateRelationship5 ()
{
PackageRelationship r = part.CreateRelationship (uris [1], TargetMode.External, "blah", null);
Assert.IsNotNull (r.Id, "#1");
Assert.AreEqual (part.Uri, r.SourceUri, "#2");
Assert.AreEqual (uris [1], r.TargetUri, "#3");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateRelationship6 ()
{
part.CreateRelationship (uris [1], TargetMode.External, "blah", "");
}
[Test]
public void CreateRelationship7 ()
{
part.CreateRelationship (uris [1], TargetMode.External, "blah", "asda");
}
[Test]
[ExpectedException (typeof (Xml.XmlException))]
public void CreateDupeRelationship ()
{
part.CreateRelationship (uris [1], TargetMode.External, "blah", "asda");
part.CreateRelationship (uris [1], TargetMode.External, "blah", "asda");
}
[Test]
[ExpectedException (typeof (Xml.XmlException))]
public void CreateDupeRelationshipId ()
{
part.CreateRelationship (uris [1], TargetMode.External, "blah", "asda");
part.CreateRelationship (uris [2], TargetMode.Internal, "aaa", "asda");
}
[Test]
public void EnumeratePartsBreak ()
{
FakePackage package = new FakePackage (FileAccess.ReadWrite, false);
package.CreatePart (uris [0], "a/a");
package.CreatePart (uris [1], "a/a");
package.CreatePart (uris [2], "a/a");
Assert.IsTrue (package.GetParts () == package.GetParts (), "#1");
try {
foreach (PackagePart part in package.GetParts ())
package.DeletePart (part.Uri);
Assert.Fail ("This should throw an exception");
} catch {
}
PackagePartCollection c = package.GetParts ();
package.CreatePart (new Uri ("/dfds", UriKind.Relative), "a/a");
int count = 0;
foreach (PackagePart p in c) { count++; }
Assert.AreEqual (3, count, "Three added, one deleted, one added");
}
[Test]
public void GetStream1 ()
{
part.GetStream ();
Assert.AreEqual (FileMode.OpenOrCreate, part.Modes [0], "#1");
Assert.AreEqual (package.FileOpenAccess, part.Accesses [0], "#2");
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void PackagePartNoContentType ()
{
string s = new FakePackagePart (package, uris [0]).ContentType;
}
[Test]
public void GetStream2 ()
{
Assert.IsNotNull (package.CreatePart (uris[1], contentType));
Assert.AreEqual (1, new List<PackagePart> (package.GetParts()).Count, "#0a");
package.Flush ();
package.Close ();
using (Package p = Package.Open (new MemoryStream (stream.ToArray ()))) {
PackagePart part = new List<PackagePart>(p.GetParts ())[0];
Stream s = part.GetStream ();
Assert.IsTrue (s.CanRead, "#1");
Assert.IsTrue (s.CanSeek, "#2");
Assert.IsFalse (s.CanWrite, "#3");
}
using (Package p = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.OpenOrCreate)) {
PackagePart part = new List<PackagePart> (p.GetParts ()) [0];
Stream s = part.GetStream ();
Assert.IsTrue (s.CanRead, "#4");
Assert.IsTrue (s.CanSeek, "#5");
Assert.IsTrue (s.CanWrite, "#6");
}
using (Package p = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
PackagePart part = new List<PackagePart> (p.GetParts ()) [0];
Stream s = part.GetStream ();
Assert.IsTrue (s.CanRead, "#7");
Assert.IsTrue (s.CanSeek, "#8");
Assert.IsTrue (s.CanWrite, "#9");
}
}
}
}

View File

@@ -0,0 +1,217 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace System.IO.Packaging.Tests
{
[TestFixture]
public class FakePackageTests : TestBase
{
//static void Main (string [] args)
//{
// FakePackageTests t = new FakePackageTests ();
// t.FixtureSetup ();
// t.Setup ();
// t.RelationshipPartGetStream ();
//}
private new FakePackage package;
public override void Setup()
{
package = new FakePackage(FileAccess.ReadWrite, true);
}
[Test]
public void CheckAutomaticParts()
{
package.CreatePart(uris[0], contentType);
Assert.AreEqual(1, package.CreatedParts.Count(), "#1");
Assert.AreEqual(uris[0], package.CreatedParts[0], "#2");
Assert.AreEqual(0, package.DeletedParts.Count(), "#3");
Assert.AreEqual(1, package.GetParts().Count(), "#4");
}
[Test]
public void CheckAutomaticParts2()
{
package.CreateRelationship(uris[0], TargetMode.External, "relationship");
Assert.AreEqual(1, package.CreatedParts.Count(), "#1");
Assert.AreEqual(relationshipUri, package.CreatedParts[0], "#2");
Assert.AreEqual(0, package.DeletedParts.Count(), "#3");
Assert.AreEqual(1, package.GetParts().Count(), "#4");
PackagePart p = package.GetPart(relationshipUri);
Assert.AreEqual(package, p.Package, "#5");
Assert.AreEqual(CompressionOption.NotCompressed, p.CompressionOption, "#6");
Assert.AreEqual("application/vnd.openxmlformats-package.relationships+xml", p.ContentType, "#7");
}
[Test]
public void CheckProperties()
{
Assert.AreEqual(0, package.GotParts.Count, "#1");
object o = package.PackageProperties;
Assert.AreEqual(1, package.GotParts.Count, "#2");
Assert.AreEqual("/_rels/.rels", package.GotParts[0].ToString(), "#3");
}
[Test]
public void RelationshipPartGetRelationships()
{
CheckAutomaticParts2();
PackagePart p = package.GetPart(relationshipUri);
try
{
p.CreateRelationship(uris[0], TargetMode.Internal, "asdas");
Assert.Fail("This should fail 1");
}
catch (InvalidOperationException)
{
}
try
{
p.DeleteRelationship("aa");
Assert.Fail("This should fail 2");
}
catch (InvalidOperationException)
{
}
try
{
p.GetRelationship("id");
Assert.Fail("This should fail 3");
}
catch (InvalidOperationException)
{
}
try
{
p.GetRelationships();
Assert.Fail("This should fail 4");
}
catch (InvalidOperationException)
{
}
try
{
p.GetRelationshipsByType("type");
Assert.Fail("This should fail 5");
}
catch (InvalidOperationException)
{
}
try
{
p.RelationshipExists("id");
Assert.Fail("This should fail 6");
}
catch (InvalidOperationException)
{
}
}
[Test]
public void TestProperties()
{
Assert.IsNotNull(package.PackageProperties, "#1");
package.PackageProperties.Title = "Title";
package.Flush();
// the relationship part and packageproperties part
Assert.AreEqual(2, package.CreatedParts.Count, "#2");
}
[Test]
public void TestWordDoc()
{
MemoryStream stream = new MemoryStream();
Package package = CreateWordDoc(stream);
Assert.IsTrue(package.PartExists(new Uri("/word/document.xml", UriKind.Relative)), "#1");
Assert.IsTrue(package.RelationshipExists("rel1"), "#2");
package.Close();
package = Package.Open(new MemoryStream(stream.ToArray()), FileMode.Open);
Assert.AreEqual(10, package.GetParts().Count(), "#3");
Assert.AreEqual (9, package.GetRelationships ().Count (), "#4");
Assert.IsTrue(package.PartExists(new Uri("/word/document.xml", UriKind.Relative)), "#5");
Assert.IsTrue(package.RelationshipExists("rel1"), "#6");
}
Package CreateWordDoc(Stream stream)
{
Package pack = Package.Open(stream, FileMode.Create);
// Create package parts.
PackagePart wordDocument = pack.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
PackagePart wordNumbering = pack.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml");
PackagePart wordStyles = pack.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
PackagePart docPropsApp = pack.CreatePart(new Uri("/docProps/app.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.extended-properties+xml");
PackagePart wordSettings = pack.CreatePart(new Uri("/word/settings.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml");
PackagePart wordTheme1 = pack.CreatePart(new Uri("/word/theme/theme1.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.theme+xml");
PackagePart wordFontTable = pack.CreatePart(new Uri("/word/fontTable.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml");
PackagePart wordWebSettings = pack.CreatePart(new Uri("/word/webSettings.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml");
PackagePart docPropsCore = pack.CreatePart(new Uri("/docProps/core.xml", UriKind.Relative), "application/vnd.openxmlformats-package.core-properties+xml");
// Create relationships for package.
pack.CreateRelationship(new Uri("docProps/app.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties");
pack.CreateRelationship(new Uri("docProps/core.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties");
pack.CreateRelationship(new Uri("word/document.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");
// Create document relationships.
pack.CreateRelationship(new Uri("settings.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings", "rel1");
pack.CreateRelationship(new Uri("styles.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", "rel2");
pack.CreateRelationship(new Uri("numbering.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", "rel3");
pack.CreateRelationship(new Uri("theme/theme1.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", "rel4");
pack.CreateRelationship(new Uri("fontTable.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable", "rel5");
pack.CreateRelationship(new Uri("webSettings.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings", "rel6");
// Load some basic data into the different parts.
foreach (PackagePart part in package.GetParts())
using (Stream s = part.GetStream())
s.Write(new byte[10], 0, 10);
return pack;
}
}
}

View File

@@ -0,0 +1,62 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
namespace System.IO.Packaging.Tests {
public class FakeStream : MemoryStream {
public bool canRead;
public bool canSeek;
public bool canWrite;
public FakeStream ()
: this (true, true, true)
{
}
public FakeStream (bool canread, bool canWrite, bool canSeek)
{
this.canRead = canread;
this.canSeek = canSeek;
this.canWrite = canWrite;
}
public override bool CanRead {
get { return canRead; }
}
public override bool CanSeek {
get { return canSeek; }
}
public override bool CanWrite {
get { return canWrite; }
}
}
}

View File

@@ -0,0 +1,355 @@
// PackUriHelperTests.cs created with MonoDevelop
// User: alan at 13:39 28/10/2008
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
using System;
using System.IO.Packaging;
using NUnit.Framework;
namespace System.IO.Packaging.Tests {
[TestFixture]
public class PackUriHelperTests {
Uri a {
get { return PackUriHelper.Create (new Uri ("http://www.test.com/pack1.pkg")); }
}
Uri b {
get { return PackUriHelper.Create (new Uri ("http://www.test.com/pack2.pkg")); }
}
Uri part1 = new Uri ("/file1", UriKind.Relative);
Uri part2 = new Uri ("/file2", UriKind.Relative);
Uri main = new Uri ("/main.html", UriKind.Relative);
[Test]
[Category("NotWorking")]
public void ComparePackUriTest ()
{
Assert.AreEqual (0, PackUriHelper.ComparePackUri (null, null), "#1");
Assert.IsTrue (PackUriHelper.ComparePackUri (a, null) > 0, "#2");
Assert.AreEqual (0, PackUriHelper.ComparePackUri (a, a), "#3");
Assert.IsTrue (PackUriHelper.ComparePackUri (a, b) < 0, "#4");
}
[Test]
[Category("NotWorking")]
[ExpectedException(typeof(UriFormatException))]
public void CompareInvalidTest ()
{
Uri a = new Uri ("pack://url1");
PackUriHelper.ComparePackUri (a, a);
}
[Test]
[Category("NotWorking")]
[ExpectedException (typeof (ArgumentException))]
public void NonPackUriCompareTest ()
{
PackUriHelper.ComparePackUri (new Uri ("http://wtest.com"), a);
}
[Test]
[Category("NotWorking")]
[ExpectedException (typeof (ArgumentException))]
public void NonPackUriCompareRelativeTest ()
{
PackUriHelper.ComparePackUri (new Uri ("wtest.com", UriKind.Relative), a);
}
[Test]
[Category("NotWorking")]
[ExpectedException (typeof (ArgumentException))]
public void InvalidPartUriCompareTest ()
{
PackUriHelper.ComparePartUri (a, b);
}
[Test]
public void PartUriCompareTest ()
{
Assert.AreEqual (0, PackUriHelper.ComparePartUri (null, null), "#1");
Assert.IsTrue (PackUriHelper.ComparePartUri (part1, null) > 0, "#2");
Assert.IsTrue (PackUriHelper.ComparePartUri (part1, part2) < 0, "#3");
}
[Test]
[Category("NotWorking")]
public void CreateTest ()
{
Assert.AreEqual ("pack://http:,,www.test.com,pack.pkg/",
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg")).ToString (), "#1");
Assert.AreEqual ("pack://http:,,www.test.com,pack.pkg/",
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"), null, null).ToString (), "#2");
Assert.AreEqual ("pack://http:,,www.test.com,pack.pkg/main.html#frag",
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"),
new Uri ("/main.html", UriKind.Relative), "#frag").ToString (), "#3");
Assert.AreEqual ("pack://http:,,www.test.com,pack.pkg/main.html#frag",
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"),
new Uri ("/main.html", UriKind.Relative), "#frag").ToString (), "#3");
}
[Test]
[Category("NotWorking")]
public void CreateTest2()
{
Uri uri = PackUriHelper.Create(new Uri("http://www.test.com/pack1.pkg"));
Assert.AreEqual("pack://pack:,,http:%2C%2Cwww.test.com%2Cpack1.pkg,/", PackUriHelper.Create(uri).ToString());
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CreateInvalidTest ()
{
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"), new Uri ("/main.html", UriKind.Relative), "notfrag");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CreateInvalidTest2 ()
{
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"), new Uri ("/main.html", UriKind.Relative), "");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CreateInvalidTest3 ()
{
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"), new Uri ("/main.html", UriKind.Relative), "");
}
[Test]
[Category("NotWorking")]
public void CreateInvalidTest4 ()
{
PackUriHelper.Create (new Uri ("http://www.test.com/pack.pkg"), new Uri ("/main.html", UriKind.Relative));
}
[Test]
public void CreatePartUri ()
{
Assert.IsFalse (PackUriHelper.CreatePartUri (part1).IsAbsoluteUri, "#1");
Assert.AreEqual (new Uri (part1.ToString (), UriKind.Relative), PackUriHelper.CreatePartUri (part1), "#2");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreatePartUri2 ()
{
PackUriHelper.CreatePartUri (null);
}
[Test]
public void GetNormalizedPartUriTest ()
{
Uri uri = new Uri ("/test.com".ToUpperInvariant (), UriKind.Relative);
Assert.IsTrue (uri == PackUriHelper.GetNormalizedPartUri (uri));
}
[Test]
public void GetNormalisedPartUritest4 ()
{
PackUriHelper.GetNormalizedPartUri (part1);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetNormalizedPartUriTest2 ()
{
PackUriHelper.GetNormalizedPartUri (null);
}
[Test]
[ExpectedException (typeof (UriFormatException))]
public void GetNormalizedPartUriTest3 ()
{
Assert.AreEqual (new Uri (a.ToString ().ToUpperInvariant (), UriKind.Relative), PackUriHelper.GetNormalizedPartUri (a));
}
[Test]
[Category("NotWorking")]
public void GetPackageUriTest ()
{
Assert.AreEqual (a, PackUriHelper.GetPackageUri (PackUriHelper.Create (a, new Uri ("/test.html", UriKind.Relative))));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetPackageUri2 ()
{
PackUriHelper.GetPackageUri (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetPackageUri3 ()
{
PackUriHelper.GetPackageUri (part1);
}
[Test]
[Category("NotWorking")]
public void GetPartUriTest ()
{
var pack = PackUriHelper.Create(new Uri("http://www.test.com/pack1.pkg"));
var part = new Uri("/main.html", UriKind.Relative);
var pack_part = new Uri(@"pack://pack:,,http:%2C%2Cwww.test.com%2Cpack1.pkg,/main.html");
Assert.IsNull(PackUriHelper.GetPartUri(pack), "#1");
Assert.AreEqual(pack_part, PackUriHelper.Create(pack, part), "#2");
Assert.AreEqual(part, PackUriHelper.GetPartUri(PackUriHelper.Create(pack, part)), "#3");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetPartUriTest2 ()
{
PackUriHelper.GetPartUri (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetPartUriTest3 ()
{
PackUriHelper.GetPartUri (part1);
}
[Test]
public void GetRelationshipPartUriTest ()
{
Assert.AreEqual ("/_rels/file1.rels", PackUriHelper.GetRelationshipPartUri (part1).ToString());
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetRelationshipPartUriTest2 ()
{
PackUriHelper.GetRelationshipPartUri (null);
}
[Test]
public void GetRelativeUriTest ()
{
Uri src = new Uri ("/1/2/3/file.jpg", UriKind.Relative);
Uri dest = new Uri ("/file2.png", UriKind.Relative);
Assert.AreEqual (new Uri ("../../../file2.png", UriKind.Relative), PackUriHelper.GetRelativeUri (src, dest), "#1");
dest = new Uri ("/1/2", UriKind.Relative);
Assert.AreEqual (new Uri ("../../2", UriKind.Relative), PackUriHelper.GetRelativeUri (src, dest), "#2");
dest = new Uri ("/1/2/", UriKind.Relative);
Assert.AreEqual (new Uri ("", UriKind.Relative), PackUriHelper.GetRelativeUri (src, src), "#4");
// See: http://msdn.microsoft.com/en-us/library/system.io.packaging.packurihelper.getrelativeuri.aspx
src = new Uri("/mydoc/markup/page.xml", UriKind.Relative);
dest = new Uri("/mydoc/markup/picture.jpg", UriKind.Relative);
Assert.AreEqual (new Uri ("picture.jpg", UriKind.Relative), PackUriHelper.GetRelativeUri (src, dest), "#5");
src = new Uri("/mydoc/markup/page.xml", UriKind.Relative);
dest = new Uri("/mydoc/picture.jpg", UriKind.Relative);
Assert.AreEqual (new Uri ("../picture.jpg", UriKind.Relative), PackUriHelper.GetRelativeUri (src, dest), "#6");
src = new Uri("/mydoc/markup/page.xml", UriKind.Relative);
dest = new Uri("/mydoc/images/picture.jpg", UriKind.Relative);
Assert.AreEqual (new Uri ("../images/picture.jpg", UriKind.Relative), PackUriHelper.GetRelativeUri (src, dest), "#7");
}
[Test]
[ExpectedException (typeof(ArgumentException))]
public void GetRelativeUriTest2 ()
{
Uri src = new Uri ("/1/2/3/file.jpg", UriKind.Relative);
Uri dest = new Uri ("/1/2/", UriKind.Relative);
Assert.AreEqual (new Uri ("../file2.png", UriKind.Relative), PackUriHelper.GetRelativeUri (src, dest), "#3");
}
[Test]
public void IsRelationshipPartUriTest ()
{
Assert.IsFalse (PackUriHelper.IsRelationshipPartUri (new Uri ("/_rels/Whatever", UriKind.Relative)));
Assert.IsTrue (PackUriHelper.IsRelationshipPartUri (new Uri ("/_rels/Whatever.rels", UriKind.Relative)));
}
[Test]
public void IsRelationshipPartUriTest2 ()
{
Uri uri = new Uri ("/test/uri", UriKind.Relative);
PackUriHelper.IsRelationshipPartUri (uri);
}
[Test]
[ExpectedException(typeof(UriFormatException))]
public void ResolvePartUri ()
{
Uri src = new Uri ("/1/2/3/4", UriKind.Relative);
Uri dest = new Uri ("/MyFile", UriKind.Relative);
// Can't be empty url
Assert.AreEqual (new Uri (""), PackUriHelper.ResolvePartUri (src, dest), "#1");
}
[Test]
//[ExpectedException (typeof (UriFormatException))]
public void ResolvePartUri2 ()
{
Uri src = new Uri ("/1/2/3/4", UriKind.Relative);
Uri dest = new Uri ("/1/2/MyFile", UriKind.Relative);
// Can't be empty url
Assert.AreEqual (new Uri ("/1/2/MyFile", UriKind.Relative), PackUriHelper.ResolvePartUri (src, dest), "#1");
Assert.AreEqual (new Uri ("/1/2/3/4", UriKind.Relative), PackUriHelper.ResolvePartUri (dest, src), "#1");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ResolvePartUri3 ()
{
Uri src = new Uri ("/1/2/3/4", UriKind.Relative);
Uri dest = new Uri ("http://www.example.com", UriKind.Absolute);
PackUriHelper.ResolvePartUri (src, dest);
}
[Test]
public void ResolvePartUri4 ()
{
Uri src = new Uri ("/", UriKind.Relative);
Uri dest = new Uri ("word/document.xml", UriKind.Relative);
Uri result = PackUriHelper.ResolvePartUri (src, dest);
Assert.IsFalse(result.IsAbsoluteUri, "#1");
Assert.AreEqual ("/word/document.xml", result.ToString(), "#2");
// See: http://msdn.microsoft.com/en-us/library/system.io.packaging.packurihelper.resolveparturi.aspx
src = new Uri ("/mydoc/markup/page.xml", UriKind.Relative);
dest = new Uri("picture.jpg", UriKind.Relative);
result = PackUriHelper.ResolvePartUri (src, dest);
Assert.AreEqual ("/mydoc/markup/picture.jpg", result.ToString(), "#3");
dest = new Uri("images/picture.jpg", UriKind.Relative);
result = PackUriHelper.ResolvePartUri (src, dest);
Assert.AreEqual ("/mydoc/markup/images/picture.jpg", result.ToString(), "#4");
dest = new Uri("./picture.jpg", UriKind.Relative);
result = PackUriHelper.ResolvePartUri (src, dest);
Assert.AreEqual ("/mydoc/markup/picture.jpg", result.ToString(), "#5");
dest = new Uri("../picture.jpg", UriKind.Relative);
result = PackUriHelper.ResolvePartUri (src, dest);
Assert.AreEqual ("/mydoc/picture.jpg", result.ToString(), "#6");
dest = new Uri("../images/picture.jpg", UriKind.Relative);
result = PackUriHelper.ResolvePartUri (src, dest);
Assert.AreEqual ("/mydoc/images/picture.jpg", result.ToString(), "#7");
src = new Uri ("/", UriKind.Relative);
dest = new Uri("images/picture.jpg", UriKind.Relative);
result = PackUriHelper.ResolvePartUri (src, dest);
Assert.AreEqual ("/images/picture.jpg", result.ToString(), "#8");
}
}
}

View File

@@ -0,0 +1,138 @@
using System;
using System.IO;
using System.IO.Packaging;
using NUnit.Framework;
namespace System.IO.Packaging.Tests
{
[TestFixture]
public class PackagePartFileTests
{
string path;
[SetUp]
public void Setup()
{
path = Path.GetTempFileName();
Package.Open(path, FileMode.Create).Close();
}
[TearDown]
public void Teardown()
{
File.Delete(path);
}
[Test]
public void TestFileMode ()
{
Uri uri =new Uri("/somepart.xml", UriKind.Relative);
FileMode[] modes = { FileMode.Open, FileMode.OpenOrCreate, FileMode.Create };
using (Package package = Package.Open(path))
{
PackagePart part;
foreach (FileMode mode in modes)
{
part = package.CreatePart(uri, "application/xml");
part.GetStream(mode, FileAccess.Write);
package.DeletePart(uri);
}
part = package.CreatePart(uri, "application/xml");
foreach (FileMode mode in modes)
part.GetStream(mode, FileAccess.Write);
}
}
[Test]
public void TestFileMode2()
{
Uri uri = new Uri("/somepart.xml", UriKind.Relative);
FileMode[] modes = { FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append };
FileMode[] otherModes = { FileMode.Open, FileMode.OpenOrCreate };
using (Package package = Package.Open(path))
{
PackagePart part = package.CreatePart(uri, "application/xml");
foreach (FileMode mode in modes)
{
try
{
part.GetStream(mode, FileAccess.Read);
throw new Exception (string.Format ("Should not be able to open with: {0}", mode));
}
catch (IOException)
{
// This should be thrown
}
}
foreach (FileMode mode in otherModes)
{
Stream s = part.GetStream(mode, FileAccess.Read);
Assert.IsTrue(s.CanRead);
Assert.IsFalse(s.CanWrite);
}
}
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CreateNewPackagePart()
{
using (Package package = Package.Open(path))
{
PackagePart part = package.CreatePart(new Uri("/somepart.xml", UriKind.Relative), "application/xml");
// CreateNew is not supported
part.GetStream(FileMode.CreateNew, FileAccess.Write);
}
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void TruncatePackagePart()
{
using (Package package = Package.Open(path))
{
PackagePart part = package.CreatePart(new Uri("/somepart.xml", UriKind.Relative), "application/xml");
// CreateNew is not supported
part.GetStream(FileMode.Truncate, FileAccess.Write);
}
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void AppendPackagePart()
{
using (Package package = Package.Open(path))
{
PackagePart part = package.CreatePart(new Uri("/somepart.xml", UriKind.Relative), "application/xml");
// CreateNew is not supported
part.GetStream(FileMode.Append, FileAccess.Write);
}
}
[Test]
public void TestOverwrite()
{
using (Package package = Package.Open(path))
{
PackagePart part = package.CreatePart(new Uri("/Uri.xml", UriKind.Relative), "content/type");
Stream s = part.GetStream(FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(s);
sw.Write("<test>aaaaaaa</test>");
sw.Flush();
Stream s5 = part.GetStream(FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw2 = new StreamWriter(s5);
sw2.Write("<test>bbb</test>");
sw2.Flush();
// Verify that the part got overwritten correctly.
Stream s6 = part.GetStream();
StreamReader sr = new StreamReader(s6);
Assert.AreEqual("<test>bbb</test>", sr.ReadToEnd());
}
}
}
}

View File

@@ -0,0 +1,193 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace System.IO.Packaging.Tests {
[TestFixture]
public class PackagePartStreamTests : TestBase {
byte [] buffer;
List<PackagePart> Parts = new List<PackagePart> ();
static void Main (string [] args)
{
PackagePartStreamTests t = new PackagePartStreamTests ();
t.FixtureSetup ();
t.Setup ();
t.CheckFlushTest ();
}
public override void FixtureSetup ()
{
base.FixtureSetup ();
Random r = new Random ();
buffer = new byte [1000];
r.NextBytes (buffer);
}
public override void Setup ()
{
base.Setup ();
Parts.Clear ();
foreach (Uri u in uris)
Parts.Add (package.CreatePart (u, "mime/type"));
}
[Test]
public void SameStreamTest ()
{
Assert.AreEqual (0, stream.Length, "#a");
package.Flush ();
Assert.IsTrue (stream.Length > 0, "#b");
Stream s1 = Parts [0].GetStream ();
Stream s2 = Parts [0].GetStream ();
Assert.IsFalse (s1 == s2, "#1");
s1.WriteByte (5);
Assert.AreEqual (1, s1.Position, "#2");
Assert.AreEqual (0, s2.Position, "#3");
Assert.AreEqual (s1.Length, s2.Length, "#4");
Assert.AreEqual (5, s2.ReadByte (), "#5");
s2.SetLength (0);
Assert.AreEqual (0, s1.Length);
}
[Test]
public void NoFlushTest ()
{
Parts [0].GetStream ().Write (buffer, 0, buffer.Length);
Assert.AreEqual (0, stream.Length);
}
[Test]
public void FlushIndividualTest ()
{
Parts [0].GetStream ().Write (buffer, 0, buffer.Length);
Parts [0].GetStream ().Flush ();
Assert.AreEqual (buffer.Length, Parts [0].GetStream ().Length, "#1");
Assert.IsTrue (stream.Length > buffer.Length, "#2");
}
[Test]
[Category ("NotWorking")]
[Ignore ("This test only works on MS.NET. Behaviour probably not easily replicatable")]
public void FlushPackageTest1 ()
{
FlushIndividualTest ();
long count = stream.Length;
package.Flush ();
Assert.IsTrue (stream.Length > count, "#1");
}
[Test]
[Category ("NotWorking")]
[Ignore ("This test is useless i believe")]
public void FlushOnlyPackage ()
{
NoFlushTest ();
package.Flush ();
long count = stream.Length;
TearDown ();
Setup ();
// FlushPackageTest1 ();
Assert.AreEqual (count, stream.Length, "#1");
}
[Test]
public void GetMultipleStreams ()
{
foreach (PackagePart p in Parts) {
p.GetStream ().Write (buffer, 0, buffer.Length);
p.GetStream ().Flush ();
Stream ssss = p.GetStream ();
bool equal = p.GetStream () == p.GetStream ();
stream.Flush ();
}
long position = stream.Length;
}
[Test]
public void FlushThenTruncate ()
{
Parts [0].GetStream ().Write (buffer, 0, buffer.Length);
package.Flush ();
Assert.IsTrue (stream.Length > buffer.Length, "#1");
Parts [0].GetStream ().SetLength (0);
package.Flush ();
Assert.IsTrue (stream.Length < buffer.Length, "#2");
long length = stream.Length;
foreach (PackagePart p in package.GetParts ().ToArray ())
package.DeletePart (p.Uri);
package.Flush ();
Assert.IsTrue (stream.Length < length, "#3");
}
[Test]
// [Category ("NotWorking")]
public void CheckFlushTest ()
{
buffer = new byte [1024 * 1024];
Assert.AreEqual (0, stream.Length, "#1");
Parts [0].GetStream ().Write (buffer, 0, buffer.Length);
Assert.AreEqual (0, stream.Length, "#2");
Assert.AreEqual (Parts[0].GetStream ().Length, buffer.Length, "#2b");
Parts [1].GetStream ().Write (buffer, 0, buffer.Length);
Assert.AreEqual (0, stream.Length, "#3");
Assert.AreEqual (Parts[1].GetStream ().Length, buffer.Length, "#3b");
Parts [0].GetStream ().Flush ();
Assert.IsTrue (stream.Length > buffer.Length * 2, "#4");
long count = stream.Length;
package.Flush ();
// FIXME: On MS.NET this works. I don't think it's worth replicating
//Assert.IsTrue (count < stream.Length, "#5");
}
[Test]
public void CheckFlushTest2 ()
{
buffer = new byte [1024 * 1024];
Assert.AreEqual (0, stream.Length, "#1");
Parts [0].GetStream ().Write (buffer, 0, buffer.Length);
Assert.AreEqual (0, stream.Length, "#2");
Parts [1].GetStream ().Write (buffer, 0, buffer.Length);
Assert.AreEqual (0, stream.Length, "#3");
package.Flush ();
Assert.IsTrue (stream.Length > buffer.Length * 2, "#4");
}
}
}

View File

@@ -0,0 +1,371 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Xml;
namespace System.IO.Packaging.Tests {
[TestFixture]
public class PackagePartTest : TestBase {
const string PackagePropertiesType = "application/vnd.openxmlformats-package.core-properties+xml";
//static void Main (string [] args)
//{
// PackagePartTest t = new PackagePartTest ();
// t.FixtureSetup ();
// t.Setup ();
// t.AddThreeParts ();
//}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void AddAbsoluteUri ()
{
package.CreatePart (new Uri ("file://lo/asd.asm", UriKind.Absolute), "aa/aa");
}
[Test]
[Category ("NotWorking")]
[Ignore ("This is a bug in the MS implementation. I don't think i can/should replicate it")]
public void AddInvalidPartTwice ()
{
try {
package.CreatePart (new Uri ("/file1.bmp", UriKind.Relative), "bmp");
} catch (ArgumentException) {
try {
package.CreatePart (new Uri ("/file1.bmp", UriKind.Relative), "bmp");
} catch (InvalidOperationException) {
Assert.AreEqual (1, package.GetParts ().Count (), "Need to be buggy and return null");
Assert.AreEqual (null, package.GetParts ().ToArray () [0], "Be buggy and add null to the internal list");
return; // Success
}
}
Assert.Fail ("Should have thrown an ArgumentException then InvalidOperationException");
}
[Test]
public void AddThreeParts ()
{
foreach (Uri u in uris)
package.CreatePart (u, "mime/type");
Assert.AreEqual (3, package.GetParts ().Count (), "Should be three parts");
PackagePartCollection c1 = package.GetParts ();
package.CreatePart (new Uri ("/asdasdas", UriKind.Relative), "asa/s");
PackagePartCollection c2 = package.GetParts ();
bool eq = c1 == c2;
Assert.IsNotNull (package.GetPart (new Uri (uris[0].ToString ().ToUpper (), UriKind.Relative)));
}
[Test]
public void CheckPartProperties ()
{
package.CreatePart (new Uri ("/first", UriKind.Relative), "my/a");
package.CreatePart (new Uri ("/second", UriKind.Relative), "my/b", CompressionOption.Maximum);
package.CreatePart (new Uri ("/third", UriKind.Relative), "test/c", CompressionOption.SuperFast);
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.Open, FileAccess.Read);
PackagePart[] parts = package.GetParts ().ToArray ();
Assert.AreEqual (3, parts.Length);
PackagePart part = parts[0];
Assert.AreEqual (CompressionOption.NotCompressed, part.CompressionOption, "Compress option wrong1");
Assert.AreEqual ("my/a", part.ContentType, "Content type wrong1");
Assert.AreEqual (package, part.Package, "Wrong package1");
Assert.AreEqual ("/first", part.Uri.ToString (), "Wrong package selected1");
part = parts[1];
Assert.AreEqual (CompressionOption.Maximum, part.CompressionOption, "Compress option wrong2");
Assert.AreEqual ("my/b", part.ContentType, "Content type wrong2");
Assert.AreEqual (package, part.Package, "Wrong package2");
Assert.AreEqual ("/second", part.Uri.OriginalString, "Wrong package selected2");
part = parts[2];
Assert.AreEqual (CompressionOption.SuperFast, part.CompressionOption, "Compress option wrong3");
Assert.AreEqual ("test/c", part.ContentType, "Content type wrong3");
Assert.AreEqual (package, part.Package, "Wrong package3");
Assert.AreEqual ("/third", part.Uri.ToString (), "Wrong package selected3");
}
[Test]
public void SameExtensionDifferentContentTypeTest ()
{
// FIXME: Ideally we should be opening the zip and checking
// exactly what was written to verify it's correct
using (var stream = new MemoryStream ()) {
var package = Package.Open (stream, FileMode.OpenOrCreate);
package.CreatePart (uris [0], contentType + "1");
package.CreatePart (uris [1], contentType + "2");
package.CreatePart (uris [2], contentType + "2");
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()));
Assert.AreEqual (contentType + "1", package.GetPart (uris [0]).ContentType, "#1");
Assert.AreEqual (contentType + "2", package.GetPart (uris [1]).ContentType, "#2");
Assert.AreEqual (contentType + "2", package.GetPart (uris [2]).ContentType, "#3");
}
}
[Test]
public void SameExtensionSameContentTypeTest ()
{
// FIXME: Ideally we should be opening the zip and checking
// exactly what was written to verify it's correct
using (var stream = new MemoryStream ()) {
var package = Package.Open (stream, FileMode.OpenOrCreate);
package.CreatePart (uris [0], contentType);
package.CreatePart (uris [1], contentType);
package.CreatePart (uris [2], contentType);
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()));
Assert.AreEqual (contentType, package.GetPart (uris [0]).ContentType, "#1");
Assert.AreEqual (contentType, package.GetPart (uris [1]).ContentType, "#2");
Assert.AreEqual (contentType, package.GetPart (uris [2]).ContentType, "#3");
}
}
[Test]
public void CheckPartRelationships ()
{
AddThreeParts ();
Assert.AreEqual (4, package.GetParts ().Count (), "#a");
PackagePart part = package.GetPart (uris [0]);
PackageRelationship r1 = part.CreateRelationship (part.Uri, TargetMode.Internal, "self");
PackageRelationship r2 = package.CreateRelationship (part.Uri, TargetMode.Internal, "fake");
PackageRelationship r3 = package.CreateRelationship (new Uri ("/fake/uri", UriKind.Relative), TargetMode.Internal, "self");
Assert.AreEqual (6, package.GetParts ().Count (), "#b");
Assert.AreEqual (1, part.GetRelationships ().Count (), "#1");
Assert.AreEqual (1, part.GetRelationshipsByType ("self").Count (), "#2");
Assert.AreEqual (r1, part.GetRelationship (r1.Id), "#3");
Assert.AreEqual (2, package.GetRelationships ().Count (), "#4");
Assert.AreEqual (1, package.GetRelationshipsByType ("self").Count (), "#5");
Assert.AreEqual (r3, package.GetRelationship (r3.Id), "#6");
Assert.AreEqual (6, package.GetParts ().Count (), "#c");
Assert.AreEqual (part.Uri, r1.SourceUri, "#7");
Assert.AreEqual (new Uri ("/", UriKind.Relative), r3.SourceUri, "#8");
PackageRelationship r4 = part.CreateRelationship (uris [2], TargetMode.Internal, "other");
Assert.AreEqual (part.Uri, r4.SourceUri);
PackageRelationshipCollection relations = package.GetPart (uris [2]).GetRelationships ();
Assert.AreEqual (0, relations.Count ());
Assert.AreEqual (6, package.GetParts ().Count (), "#d");
}
[Test]
public void CheckIndividualRelationships ()
{
PackagePart part = package.CreatePart (uris [0], contentType);
part.CreateRelationship (uris [1], TargetMode.Internal, "relType");
part.CreateRelationship (uris [2], TargetMode.External, "relType");
package.Flush ();
Assert.AreEqual (2, package.GetParts ().Count(), "#1");
part = package.GetPart (new Uri ("/_rels" + uris [0].ToString () + ".rels", UriKind.Relative));
Assert.IsNotNull (part);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void DeletePartsAfterAddingRelationships ()
{
CheckPartRelationships ();
foreach (PackagePart p in new List<PackagePart> (package.GetParts ()))
package.DeletePart (p.Uri);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void DeleteRelsThenParts ()
{
CheckPartRelationships ();
foreach (PackageRelationship r in new List<PackageRelationship> (package.GetRelationships ()))
package.DeleteRelationship (r.Id);
foreach (PackagePart p in new List<PackagePart> (package.GetParts ()))
package.DeletePart (p.Uri);
}
[Test]
public void CreateValidPart ()
{
PackagePart part = package.CreatePart (uris [0], "img/bmp");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void CreateDuplicatePart ()
{
CreateValidPart ();
CreateValidPart ();
}
[Test]
public void CreateValidPartTwice ()
{
CreateValidPart ();
package.DeletePart (uris [0]);
CreateValidPart ();
Assert.AreEqual (1, package.GetParts ().Count (), "#1");
Assert.AreEqual (uris [0], package.GetParts ().ToArray () [0].Uri, "#2");
package.DeletePart (uris [0]);
package.DeletePart (uris [0]);
package.DeletePart (uris [0]);
}
[Test]
public void IterateParts ()
{
List<PackagePart> parts = new List<PackagePart> ();
parts.Add (package.CreatePart (new Uri ("/a", UriKind.Relative), "mime/type"));
parts.Add (package.CreatePart (new Uri ("/b", UriKind.Relative), "mime/type"));
List<PackagePart> found = new List<PackagePart> (package.GetParts ());
Assert.AreEqual (parts.Count, found.Count, "Invalid number of parts");
Assert.IsTrue (found.Contains (parts [0]), "Doesn't contain first part");
Assert.IsTrue (found.Contains (parts [1]), "Doesn't contain second part");
Assert.IsTrue (found [0] == parts [0] || found [0] == parts [1], "Same object reference should be used");
Assert.IsTrue (found [1] == parts [0] || found [1] == parts [1], "Same object reference should be used");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void NoStartingSlashPartialUri ()
{
PackagePart part = package.CreatePart (new Uri ("file1.bmp", UriKind.Relative), "bmp");
}
[Test]
public void PackagePropertiesTest ()
{
package.PackageProperties.Category = "category";
package.PackageProperties.ContentStatus = "status";
package.PackageProperties.ContentType = "contentttype";
package.PackageProperties.Created = new DateTime (2008, 12, 12, 2, 3, 4);
package.PackageProperties.Creator = "mono";
package.PackageProperties.Description = "description";
package.PackageProperties.Identifier = "id";
package.PackageProperties.Keywords = "key words";
package.PackageProperties.Language = "english";
package.PackageProperties.LastModifiedBy = "modified";
package.PackageProperties.LastPrinted = new DateTime (2007, 12, 12, 2, 3, 4);
package.PackageProperties.Modified = new DateTime (2008, 12, 12, 3, 4, 5);
package.PackageProperties.Revision = "reviison";
package.PackageProperties.Subject = "subject";
package.PackageProperties.Title = "title";
package.PackageProperties.Version = "version";
Assert.AreEqual (0, package.GetParts ().Count (), "#1");
package.Flush ();
Assert.AreEqual (2, package.GetParts ().Count (), "#2");
var part = package.GetParts ().Where (p => p.ContentType == PackagePropertiesType).ToList ().First ();
Assert.IsNotNull (part);
Assert.IsTrue (part.Uri.OriginalString.StartsWith ("/package/services/metadata/core-properties/"), "#3");
Assert.IsTrue (part.Uri.OriginalString.EndsWith (".psmdcp"), "#4");
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()));
Assert.AreEqual (package.PackageProperties.Category, "category", "#5");
Assert.AreEqual (package.PackageProperties.ContentStatus, "status", "#6");
Assert.AreEqual (package.PackageProperties.ContentType, "contentttype", "#7");
Assert.AreEqual (package.PackageProperties.Created, new DateTime (2008, 12, 12, 2, 3, 4), "#8");
Assert.AreEqual (package.PackageProperties.Creator, "mono", "#9");
Assert.AreEqual (package.PackageProperties.Description, "description", "#10");
Assert.AreEqual (package.PackageProperties.Identifier, "id", "#11");
Assert.AreEqual (package.PackageProperties.Keywords, "key words", "#12");
Assert.AreEqual (package.PackageProperties.Language, "english", "#13");
Assert.AreEqual (package.PackageProperties.LastModifiedBy, "modified", "#14");
Assert.AreEqual (package.PackageProperties.LastPrinted, new DateTime (2007, 12, 12, 2, 3, 4), "#15");
Assert.AreEqual (package.PackageProperties.Modified, new DateTime (2008, 12, 12, 3, 4, 5), "#16");
Assert.AreEqual (package.PackageProperties.Revision, "reviison", "#17");
Assert.AreEqual (package.PackageProperties.Subject, "subject", "#18");
Assert.AreEqual (package.PackageProperties.Title, "title", "#19");
Assert.AreEqual (package.PackageProperties.Version, "version", "#20");
}
[Test]
public void PackagePropertiestest2 ()
{
package.PackageProperties.Title = "TITLE";
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()));
Assert.AreEqual (null, package.PackageProperties.Category, "#1");
}
[Test]
[ExpectedException (typeof (IOException))]
public void PackagePropertiesReadonly ()
{
PackagePropertiesTest ();
package.PackageProperties.Title = "Title";
}
[Test]
public void PartExists ()
{
CreateValidPart ();
Assert.IsNotNull (package.GetPart (uris [0]), "Part could not be found");
Assert.IsTrue (package.PartExists (uris [0]), "Part didn't exist");
Assert.AreEqual (1, package.GetParts ().Count (), "Only one part");
}
[Test]
public void RemoveThreeParts ()
{
AddThreeParts ();
foreach (PackagePart p in new List<PackagePart> (package.GetParts ()))
package.DeletePart (p.Uri);
Assert.AreEqual (0, package.GetParts ().Count (), "Should contain no parts");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void RemoveThreePartsBreak ()
{
AddThreeParts ();
foreach (PackagePart p in package.GetParts ())
package.DeletePart (p.Uri);
}
[Test]
public void CheckContentTypes ()
{
Assert.IsFalse (package.PartExists(new Uri ("[Content_Types].xml", UriKind.Relative)));
}
}
}

View File

@@ -0,0 +1,186 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2011 Xamarin Inc. (http://www.xamarin.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
// Rolf Bjarne Kvinge (rolf@xamarin.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using NUnit.Framework;
namespace System.IO.Packaging.Tests {
[TestFixture]
public class PackageRelationshipTests : TestBase {
[Test]
public void AddInvalidRelationshipTwice ()
{
try {
package.CreateRelationship (new Uri ("", UriKind.Relative), TargetMode.Internal, "bmp");
} catch (ArgumentException) {
try {
package.CreateRelationship (new Uri ("", UriKind.Relative), TargetMode.Internal, "bmp");
} catch (ArgumentException) {
Assert.AreEqual (0, package.GetRelationships ().Count (), "Need to be buggy and return null");
return; // Success
}
}
Assert.Fail ("Should have thrown an ArgumentException then InvalidOperationException");
}
[Test]
public void AddThreeRelationShips ()
{
PackageRelationship r1 = package.CreateRelationship (uris [0], TargetMode.Internal, "a");
PackageRelationship r2 = package.CreateRelationship (uris [1], TargetMode.Internal, "b");
PackageRelationship r3 = package.CreateRelationship (uris [2], TargetMode.Internal, "a");
Assert.AreEqual (3, package.GetRelationships ().Count (), "#1");
Assert.AreEqual (2, package.GetRelationshipsByType ("a").Count (), "#2");
Assert.AreEqual (0, package.GetRelationshipsByType ("A").Count (), "#3");
}
[Test]
public void CheckProperties ()
{
AddThreeRelationShips ();
PackageRelationship r = package.GetRelationshipsByType ("b").ToArray () [0];
Assert.AreEqual (uris [1], r.TargetUri, "#1");
Assert.AreEqual (TargetMode.Internal, r.TargetMode, "#2");
Assert.AreEqual (new Uri ("/", UriKind.Relative), r.SourceUri, "#3");
Assert.AreEqual ("b", r.RelationshipType, "#4");
Assert.AreEqual (package, r.Package, "#5");
Assert.IsTrue (package == r.Package, "#6");
Assert.IsTrue (!string.IsNullOrEmpty (r.Id), "#7");
Assert.IsTrue (char.IsLetter (r.Id [0]), "#8");
}
[Test]
public void CreatePackageTest ()
{
package.CreateRelationship (uris[0], TargetMode.Internal, "a");
package.CreateRelationship (uris[1], TargetMode.External, "a");
package.CreateRelationship (new Uri ("http://www.example.com", UriKind.Absolute), TargetMode.External, "ex");
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()));
PackageRelationship[] rels = package.GetRelationships ().ToArray ();
Assert.AreEqual (3, rels.Length, "#1");
Assert.AreEqual (uris[0], rels[0].TargetUri, "#2");
Assert.AreEqual (TargetMode.Internal, rels[0].TargetMode, "#3");
Assert.AreEqual (uris[1], rels[1].TargetUri, "#4");
Assert.AreEqual (TargetMode.External, rels[1].TargetMode, "#5");
Assert.AreEqual ("http://www.example.com/", rels[2].TargetUri.ToString (), "#6");
Assert.AreEqual (TargetMode.External, rels[1].TargetMode, "#7");
}
[Test]
public void ExternalRelationshipTest ()
{
package.CreateRelationship (new Uri ("/file2", UriKind.Relative), TargetMode.External, "RelType");
package.CreateRelationship (new Uri ("http://www.example.com", UriKind.Absolute), TargetMode.External, "RelType");
}
[Test]
public void InternalRelationshipTest ()
{
package.CreateRelationship (new Uri ("/file2", UriKind.Relative), TargetMode.Internal, "RelType");
try {
package.CreateRelationship (new Uri ("http://www.example.com", UriKind.Absolute), TargetMode.Internal, "RelType");
Assert.Fail ("Internal relationships must be relative");
} catch (ArgumentException) {
}
}
[Test]
public void RemoveById ()
{
AddThreeRelationShips ();
PackageRelationship r = package.GetRelationshipsByType ("a").ToArray () [0];
package.DeleteRelationship (r.Id);
Assert.AreEqual (2, package.GetRelationships ().Count (), "#1");
Assert.AreEqual (1, package.GetRelationshipsByType ("a").Count (), "#2");
}
[Test]
public void RemoveThreeRelationships ()
{
AddThreeRelationShips ();
foreach (PackageRelationship p in new List<PackageRelationship> (package.GetRelationships ()))
package.DeleteRelationship (p.Id);
Assert.AreEqual (0, package.GetRelationships ().Count (), "Should contain no relationships");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void RemoveThreeRelationshipsBreak ()
{
AddThreeRelationShips ();
foreach (PackageRelationship p in package.GetRelationships ())
package.DeleteRelationship (p.Id);
}
[Test]
public void CheckRelationshipData ()
{
AddThreeRelationShips ();
PackagePart part = package.GetPart (new Uri ("/_rels/.rels", UriKind.Relative));
Assert.IsNotNull (package.GetPart (new Uri ("/_RELS/.RELS", UriKind.Relative)), "#0");
package.Flush ();
Assert.IsNotNull (part, "#1");
Stream stream = part.GetStream ();
Assert.IsTrue (stream.Length > 0, "#2a");
XmlDocument doc = new XmlDocument ();
XmlNamespaceManager manager = new XmlNamespaceManager (doc.NameTable);
manager.AddNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
doc.Load (new StreamReader (stream));
Assert.IsNotNull (doc.SelectSingleNode ("/rel:Relationships", manager), "#2b");
XmlNodeList list = doc.SelectNodes ("/rel:Relationships/*", manager);
Assert.AreEqual (3, list.Count);
List<PackageRelationship> relationships = new List<PackageRelationship>(package.GetRelationships ());
foreach (XmlNode node in list) {
Assert.AreEqual (3, node.Attributes.Count, "#3");
Assert.IsNotNull (node.Attributes ["Id"], "#4");
Assert.IsNotNull (node.Attributes ["Target"], "#5");
Assert.IsNotNull (node.Attributes ["Type"], "#6");
Assert.IsTrue(relationships.Exists(d => d.Id == node.Attributes["Id"].InnerText &&
d.TargetUri == new Uri (node.Attributes["Target"].InnerText, UriKind.Relative) &&
d.RelationshipType == node.Attributes["Type"].InnerText));
}
}
}
}

View File

@@ -0,0 +1,418 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Alan McGovern (amcgovern@novell.com)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace System.IO.Packaging.Tests {
[TestFixture]
public class PackageTest : TestBase {
//static void Main (string [] args)
//{
// PackageTest t = new PackageTest ();
// t.FixtureSetup ();
// t.Setup ();
// t.RelationshipPartGetStream ();
//}
string path = "test.package";
public override void Setup ()
{
if (File.Exists (path))
File.Delete (path);
}
public override void TearDown ()
{
try {
if (package != null)
package.Close ();
} catch {
// FIXME: This shouldn't be required when i implement this
}
if (File.Exists (path))
File.Delete (path);
}
[Test]
public void CheckContentFile ()
{
MemoryStream stream = new MemoryStream ();
package = Package.Open (stream, FileMode.Create, FileAccess.ReadWrite);
package.CreatePart (uris[0], "custom/type");
package.CreateRelationship (uris[1], TargetMode.External, "relType");
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.Open, FileAccess.ReadWrite);
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.Open, FileAccess.ReadWrite);
Assert.AreEqual (2, package.GetParts ().Count (), "#1");
Assert.AreEqual (1, package.GetRelationships ().Count (), "#2");
}
[Test]
[ExpectedException (typeof (FileFormatException))]
public void CorruptStream ()
{
stream = new FakeStream (true, true, true);
stream.Write (new byte [1024], 0, 1024);
package = Package.Open (stream);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void FileShareReadWrite ()
{
package = Package.Open (path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
}
[Test]
[ExpectedException (typeof (FileNotFoundException))]
public void OpenNonExistantPath ()
{
package = Package.Open (path, FileMode.Open);
}
[Test]
public void NonExistantPath ()
{
package = Package.Open (path);
}
[Test]
public void PreExistingPath ()
{
package = Package.Open (path);
package.Close ();
package = Package.Open (path);
}
[Test]
public void Close_FileStreamNotClosed ()
{
using (var stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
var package = Package.Open (stream, FileMode.OpenOrCreate);
package.CreatePart (uris [0], contentType);
package.Close ();
stream.Read (new byte [1024], 0, 1024);
}
}
[Test]
public void Close_MemoryStreamNotClosed ()
{
using (var stream = new MemoryStream ()) {
var package = Package.Open (stream, FileMode.OpenOrCreate);
package.CreatePart (uris [0], contentType);
package.Close ();
stream.Read (new byte [1024], 0, 1024);
}
}
[Test]
public void Close_Twice ()
{
var package = Package.Open (new MemoryStream (), FileMode.OpenOrCreate);
package.Close ();
package.Close ();
}
[Test]
public void Dispose_Twice ()
{
var package = Package.Open (new MemoryStream (), FileMode.OpenOrCreate);
((IDisposable) package).Dispose ();
((IDisposable) package).Dispose ();
}
[Test]
public void CreatePath ()
{
package = Package.Open (path, FileMode.Create);
Assert.AreEqual (FileAccess.ReadWrite, package.FileOpenAccess, "#1");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CreatePathReadonly ()
{
package = Package.Open (path, FileMode.Create, FileAccess.Read);
package.Close ();
}
[Test]
public void CreatePathTwice ()
{
package = Package.Open (path, FileMode.Create);
package.Close ();
package = Package.Open (path, FileMode.Open);
Assert.AreEqual (FileAccess.ReadWrite, package.FileOpenAccess);
}
[Test]
public void OpenPackageMultipleTimes ()
{
var filename = Path.GetTempFileName ();
try {
using (var file = File.Open (filename, FileMode.OpenOrCreate)) {
var package = Package.Open (file, FileMode.OpenOrCreate);
var part = package.CreatePart (new Uri ("/test", UriKind.Relative), "test/type");
using (var stream = part.GetStream ())
stream.Write (new byte [1024 * 1024], 0, 1024 * 1024);
package.Close ();
}
for (int i = 0; i < 10; i++) {
using (var file = File.Open (filename, FileMode.OpenOrCreate))
using (var package = Package.Open (file)) {
package.GetParts ();
package.GetRelationships ();
}
}
} finally {
if (File.Exists (filename))
File.Delete (filename);
}
}
[Test]
public void OpenPathReadonly ()
{
package = Package.Open (path, FileMode.Create);
package.CreatePart (uris[0], contentType);
package.CreateRelationship (uris[1], TargetMode.External, "relType");
package.Close ();
package = Package.Open (path, FileMode.Open, FileAccess.Read);
Assert.AreEqual (2, package.GetParts ().Count (), "#1");
Assert.AreEqual (1, package.GetRelationships ().Count (), "#2");
Assert.AreEqual (FileAccess.Read, package.FileOpenAccess, "Should be read access");
try {
package.CreatePart (uris [0], contentType);
Assert.Fail ("Cannot modify a read-only package");
} catch (IOException) {
}
try {
package.CreateRelationship (uris [0], TargetMode.Internal, contentType);
Assert.Fail ("Cannot modify a read-only package");
} catch (IOException) {
}
try {
package.DeletePart (uris [0]);
Assert.Fail ("Cannot modify a read-only package");
} catch (IOException) {
}
try {
package.DeleteRelationship (contentType);
Assert.Fail ("Cannot modify a read-only package");
} catch (IOException) {
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ReadableStream ()
{
stream = new FakeStream (true, false, false);
package = Package.Open (stream);
}
[Test]
[ExpectedException (typeof (FileFormatException))]
public void ReadableSeekableStream ()
{
stream = new FakeStream (true, false, true);
package = Package.Open (stream);
try {
package.DeleteRelationship (contentType);
Assert.Fail ("Cannot modify a read-only package");
} catch (IOException) {
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ReadOnlyAccess ()
{
stream = new FakeStream (true, false, true);
package = Package.Open (path, FileMode.CreateNew, FileAccess.Read);
try {
package.DeleteRelationship (contentType);
Assert.Fail ("Cannot modify a read-only package");
} catch (IOException) {
}
}
[Test]
[Category ("NotWorking")]
[Ignore ("I'm not supposed to write to the relation stream unless i'm flushing")]
public void RelationshipPartGetStream ()
{
package = Package.Open (path);
package.CreateRelationship (uris [0], TargetMode.External, "rel");
PackagePart p = package.GetPart (relationshipUri);
Assert.IsNotNull (p, "#0");
Stream s = p.GetStream ();
Assert.AreEqual (0, s.Length, "#1");
Assert.IsTrue (s.CanRead, "#2");
Assert.IsTrue (s.CanSeek, "#3");
Assert.IsFalse (s.CanTimeout, "#4");
Assert.IsTrue (s.CanWrite, "#5");
}
[Test]
[ExpectedException (typeof (IOException))]
public void SetFileModeOnUnwriteableStream ()
{
stream = new FakeStream (true, false, true);
package = Package.Open (stream, FileMode.Truncate);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void SetAppendOnWriteableStream ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.Append);
}
[Test]
public void SetCreateNewOnWriteableStream ()
{
package = Package.Open (stream, FileMode.CreateNew);
}
[Test]
[ExpectedException(typeof(IOException))]
public void SetCreateNewOnWriteableStream2 ()
{
stream = new FakeStream (true, true, true);
stream.Write (new byte [1000], 0, 1000);
package = Package.Open (stream, FileMode.CreateNew);
Assert.AreEqual (0, stream.Length, "#1");
}
[Test]
public void SetCreateOnWriteableStream ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.Create);
}
[Test]
[ExpectedException (typeof (FileFormatException))]
public void SetOpenOnWriteableStream ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.Open);
}
[Test]
public void SetOpenOrCreateOnWriteableStream ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.OpenOrCreate);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void SetTruncateOnWriteableStream ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.Truncate);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void SetTruncateOnWriteablePath ()
{
stream = new FakeStream (true, true, true);
File.Create (path).Close ();
package = Package.Open (path, FileMode.Truncate);
}
[Test]
[ExpectedException (typeof (FileFormatException))]
public void StreamOpen ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.Open);
}
[Test]
public void StreamCreate ()
{
stream = new FakeStream (true, true, true);
package = Package.Open (stream, FileMode.Create);
}
[Test]
[ExpectedException (typeof (IOException))]
public void UnusableStream ()
{
stream = new FakeStream (false, false, false);
package = Package.Open (stream);
}
// Bug - I'm passing in FileAccess.Write but it thinks I've passed FileAccess.Read
[Test]
[ExpectedException (typeof (ArgumentException))]
public void WriteAccessDoesntExist ()
{
package = Package.Open (path, FileMode.OpenOrCreate, FileAccess.Write);
}
[Test]
public void ReadWriteAccessDoesntExist ()
{
package = Package.Open (path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
}
[Test]
[ExpectedException (typeof (FileFormatException))]
public void WriteOnlyAccessExists ()
{
System.IO.File.Create (path).Close ();
package = Package.Open (path, FileMode.OpenOrCreate, FileAccess.Write);
}
}
}

Some files were not shown because too many files have changed in this diff Show More