ronantakizawa/codereview-bench huggingface dataset:
Repository: opencv/opencv
File: modules/core/test/test_mat.cpp (C++)

Code before:

    for(int row=4; row<a.rows; row++) {

        for(int col=0; col<a.cols; col++) {

            ASSERT_FLOAT_EQ(1.f, a.at<float>(row, col));
        }
    }
}

TEST(Core_Mat, copyToConvertTo_Empty)
{
    cv::Mat A(0, 0, CV_16SC2), B, C;
    A.copyTo(B);
    ASSERT_EQ(A.type(), B.type());
    A.convertTo(C, CV_32SC2);
    ASSERT_EQ(C.type(), CV_32SC2);
}

// Regression test for https://github.com/opencv/opencv/issues/28343
// copyTo on empty fixed-type matrices should be a no-op and succeed
TEST(Core_Mat, copyTo_EmptyFixedType)
{
    cv::Mat_<double> a;
    cv::Mat_<double> b;
    ASSERT_TRUE(a.empty());
    EXPECT_NO_THROW(a.copyTo(b));
    EXPECT_TRUE(b.empty());
    // Verify type is still consistent after copyTo
    EXPECT_EQ(b.type(), CV_64F);
}

TEST(Core_Mat, copyNx1ToVector)
{
    cv::Mat_<uchar> src(5, 1);
    cv::Mat_<uchar> ref_dst8;
    cv::Mat_<ushort> ref_dst16;
    std::vector<uchar> dst8;
    std::vector<ushort> dst16;

    src << 1, 2, 3, 4, 5;

    src.copyTo(ref_dst8);
    src.copyTo(dst8);

    ASSERT_PRED_FORMAT2(cvtest::MatComparator(0, 0), ref_dst8, cv::Mat_<uchar>(dst8));

    src.convertTo(ref_dst16, CV_16U);
    src.convertTo(dst16, CV_16U);

    ASSERT_PRED_FORMAT2(cvtest::MatComparator(0, 0), ref_dst16, cv::Mat_<ushort>(dst16));

Review comment (suggestion):
I believe this assertion is redundant since it is implied by the subsequent test on `b`.

Code after:

    for(int row=4; row<a.rows; row++) {

        for(int col=0; col<a.cols; col++) {

            ASSERT_FLOAT_EQ(1.f, a.at<float>(row, col));
        }
    }
}

TEST(Core_Mat, copyToConvertTo_Empty)
{
    cv::Mat A(0, 0, CV_16SC2), B, C;
    A.copyTo(B);
    ASSERT_EQ(A.type(), B.type());
    A.convertTo(C, CV_32SC2);
    ASSERT_EQ(C.type(), CV_32SC2);
}

// Regression test for https://github.com/opencv/opencv/issues/28343
// copyTo on empty fixed-type matrices should be a no-op and succeed
template <typename T> class Core_Mat_copyTo : public testing::Test {};
TYPED_TEST_CASE_P(Core_Mat_copyTo);

TYPED_TEST_P(Core_Mat_copyTo, EmptyFixedType)
{
    cv::Mat_<TypeParam> a;
    cv::Mat_<TypeParam> b;
    EXPECT_NO_THROW(a.copyTo(b));
    EXPECT_TRUE(b.empty());
    // Verify type is still consistent after copyTo
    EXPECT_EQ(b.type(), cv::traits::Type<TypeParam>::value);
}

REGISTER_TYPED_TEST_CASE_P(Core_Mat_copyTo, EmptyFixedType);
typedef ::testing::Types<uchar, schar, ushort, short, int, float, double> AllMatDepths;
INSTANTIATE_TYPED_TEST_CASE_P(CopyToTest, Core_Mat_copyTo, AllMatDepths);

TEST(Core_Mat, copyNx1ToVector)
{
    cv::Mat_<uchar> src(5, 1);
    cv::Mat_<uchar> ref_dst8;
    cv::Mat_<ushort> ref_dst16;
    std::vector<uchar> dst8;
    std::vector<ushort> dst16;

    src << 1, 2, 3, 4, 5;

    src.copyTo(ref_dst8);
    src.copyTo(dst8);
Repository: opencv/opencv
File: modules/dnn/perf/perf_resize.cpp (C++)

Code before:
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

#include "perf_precomp.hpp"

namespace opencv_test {

struct Layer_Resize : public TestBaseWithParam<tuple<Backend, Target>>
{
    void test_layer(const std::vector<int>& inpShape, int outH, int outW, const String& interp)
    {
        int backendId = get<0>(GetParam());
        int targetId = get<1>(GetParam());

        Mat input(inpShape, CV_32FC1);
        randu(input, 0.f, 1.f);

        Net net;
        LayerParams lp;
        lp.type = "Resize";
        lp.name = "testLayer";
        lp.set("interpolation", interp);
        lp.set("width", outW);
        lp.set("height", outH);
        


        int id = net.addLayerToPrev(lp.name, lp.type, lp);
        net.connect(0, 0, id, 0);

        // warmup
        {
            net.setInputsNames({"data"});

Review comment (suggestion):
As soon as the perf test covers CPU only, I propose to implement simple PERF_TEST_P. It allows to dtop dnnBackendsAndTargets call and get just all combinations of test parameters e.g. size and interpolation type.

Code after:
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

#include "perf_precomp.hpp"

namespace opencv_test {

struct Layer_Resize : public TestBaseWithParam<tuple<Backend, Target>>
{
    void test_layer(const std::vector<int>& inpShape, int outH, int outW, const String& interp)
    {
        int backendId = get<0>(GetParam());
        int targetId = get<1>(GetParam());

        Mat input(inpShape, CV_32FC1);
        randu(input, 0.f, 1.f);

        Net net;
        LayerParams lp;
        lp.type = "Resize";
        lp.name = "testLayer";
        lp.set("interpolation", interp);
        lp.set("width", outW);
        lp.set("height", outH);



        int id = net.addLayerToPrev(lp.name, lp.type, lp);
        net.connect(0, 0, id, 0);

        // warmup
        {
            net.setInputsNames({"data"});
Repository: opentofu/opentofu
File: internal/copy/copy_dir.go (Go)

Code before:

		if err := copyFile(dstPath, path, info.Mode()); err != nil {
			return err
		}

		return nil
	}

	return filepath.Walk(src, walkFn)
}

// copyFile copies the contents and mode of the file from src to dst.
func copyFile(dst, src string, mode os.FileMode) error {
	srcF, err := os.Open(src)
	if err != nil {
		return fmt.Errorf("failed to open source file %q: %w", src, err)
	}
	defer srcF.Close()

	dstF, err := os.Create(dst)
	if err != nil {
		return fmt.Errorf("failed to create destination file %q: %w", dst, err)
	}
	defer func() {
		if cerr := dstF.Close(); cerr != nil {
			err = fmt.Errorf("failed to close destination file %q: %w", dst, cerr)
		}
	}()

	if _, err := io.Copy(dstF, srcF); err != nil {
		return fmt.Errorf("failed to copy contents from %q to %q: %w", src, dst, err)
	}

	if err := os.Chmod(dst, mode); err != nil {
		return fmt.Errorf("failed to set file mode for %q: %w", dst, err)
	}

	return nil
}

// SameFile returns true if the two given paths refer to the same physical
// file on disk, using the unique file identifiers from the underlying
// operating system. For example, on Unix systems this checks whether the
// two files are on the same device and have the same inode.
func SameFile(a, b string) (bool, error) {
	if a == b {
		return true, nil
	}

	aInfo, err := os.Lstat(a)
	if err != nil {

Review comment (suggestion):
I think this statement does nothing. `err` is not going to be overridden here (even if it would, we should be careful to not wipe the original error). We can just leave it as it was (`defer dstF.Close()`) or we can put some logging in here. In any case let's not try to override the `err`.

Code after:
		return copyFile(dstPath, path, info.Mode())
	}
	return filepath.Walk(src, walkFn)
}

// copyFile copies the contents and mode of the file from src to dst.
func copyFile(dst, src string, mode os.FileMode) error {
	srcF, err := os.Open(src)
	if err != nil {
		return fmt.Errorf("failed to open source file %q: %w", src, err)
	}
	defer srcF.Close()

	dstF, err := os.Create(dst)
	if err != nil {
		return fmt.Errorf("failed to create destination file %q: %w", dst, err)
	}

	if _, err := io.Copy(dstF, srcF); err != nil {
		dstF.Close() // Ignore error from Close since io.Copy already failed
		return fmt.Errorf("failed to copy contents from %q to %q: %w", src, dst, err)
	}

	if err := dstF.Close(); err != nil {
		return fmt.Errorf("failed to close destination file %q: %w", dst, err)
	}

	if err := os.Chmod(dst, mode); err != nil {
		return fmt.Errorf("failed to set file mode for %q: %w", dst, err)
	}

	return nil
}

// SameFile returns true if the two given paths refer to the same physical
// file on disk, using the unique file identifiers from the underlying
// operating system. For example, on Unix systems this checks whether the
// two files are on the same device and have the same inode.
func SameFile(a, b string) (bool, error) {
	if a == b {
		return true, nil
	}

	aInfo, err := os.Lstat(a)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
Repository: opentofu/opentofu
File: internal/backend/remote-state/http/helper.go (Go)

Code before:
// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2023 HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package http

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
)

// Helper function to parse response body bytes into a string for logging
func parseResponseBody(resp *http.Response) string {
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("[ERROR] Failed to read HTTP response body for Logging: %v", err)
		return ""
	}
	return string(body)
}

// Helper function to parse http headers into a json string for logging
func parseHeaders(resp *http.Response) string {
	// Blacklist of Header keys that need to be masked
	var blacklist = map[string]bool{
		"Authorization": true,
		"Cookie":        true,
		"Set-Cookie":    true,
	}

	headers := make(map[string]string, len(resp.Header))
	for key := range resp.Header {
		if blacklist[key] {
			headers[key] = "[MASKED]"
		} else {
			headers[key] = resp.Header.Get(key)
		}
	}

Review comment (suggestion):
nit: `parseResponseBody` and `parseHeaders` should only be used for logging purposes and I would suggest reflecting this in their naming. Something like `prepareResponseBodyForLog` / `parseResponseBodyForLog`

Code after:
// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2023 HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package http

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"strings"
)

// Helper function to parse response body bytes into a string for logging
func parseResponseBodyForLog(resp *http.Response) string {
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("[ERROR] Failed to read HTTP response body for Logging: %v", err)
		return ""
	}
	return string(body)
}

// Helper function to parse http headers into a json string for logging
func parseHeadersForLog(resp *http.Response) string {
	// Blacklist of Header keys that need to be masked
	var blacklist = map[string]bool{
		"authorization": true,
		"cookie":        true,
		"set-cookie":    true,
	}

	headers := make(map[string]string, len(resp.Header))
	for key := range resp.Header {
		if blacklist[strings.ToLower(key)] {
			headers[key] = "[MASKED]"
		} else {
			headers[key] = resp.Header.Get(key)
		}
Repository: opentofu/opentofu
File: internal/encryption/base.go (Go)

Code before:

	// TODO Discuss if we should potentially cache this based on a json-encoded version of inputData.Meta and reduce overhead dramatically
	methods, diags := base.buildTargetMethods(inputData.Meta, outputData.Meta)
	if diags.HasErrors() {
		// This cast to error here is safe as we know that at least one error exists
		// This is also quite unlikely to happen as the constructor already has checked this code path
		return nil, StatusUnknown, diags
	}

	errs := make([]error, 0)
	for i, method := range methods {
		if unencrypted.Is(method) {
			// Not applicable
			continue
		}
		uncd, err := method.Decrypt(inputData.Data)
		if err == nil {
			// Success
			if i == 0 {
				// Decrypted with first method (encryption method)
				return uncd, StatusSatisfied, nil
			} else {
				// Used a fallback
				return uncd, StatusMigration, nil
			}
		}
		// Record the failure
		errs = append(errs, fmt.Errorf("attempted decryption failed for %s: %w", base.name, err))
	}

	// This is good enough for now until we have better/distinct errors
	errMessage := "decryption failed for all provided methods: "
	sep := ""
	for _, err := range errs {
		errMessage += err.Error() + sep
		sep = "\n"
	}
	return nil, StatusUnknown, fmt.Errorf(errMessage)
}


Review comment (suggestion):
I don't love the fact that now `decrypt` is aware of the configuration detail where the first method is the encryption method, and the second is the fallback.

But I can't really think of a prettier way of doing this right now

Code after:
	outputData := basedata{
		Meta: make(map[keyprovider.MetaStorageKey][]byte),
	}

	if inputData.Version != encryptionVersion {
		return nil, StatusUnknown, fmt.Errorf("invalid encrypted payload version: %s != %s", inputData.Version, encryptionVersion)
	}

	// TODO Discuss if we should potentially cache this based on a json-encoded version of inputData.Meta and reduce overhead dramatically
	methods, diags := base.buildTargetMethods(inputData.Meta, outputData.Meta)
	if diags.HasErrors() {
		// This cast to error here is safe as we know that at least one error exists
		// This is also quite unlikely to happen as the constructor already has checked this code path
		return nil, StatusUnknown, diags
	}

	errs := make([]error, 0)
	for i, method := range methods {
		if unencrypted.Is(method) {
			// Not applicable
			continue
		}
		uncd, err := method.Decrypt(inputData.Data)
		if err == nil {
			// Success
			if i == 0 {
				// Decrypted with first method (encryption method)
				return uncd, StatusSatisfied, nil
			}
			// Used a fallback
			return uncd, StatusMigration, nil
		}
		// Record the failure
		errs = append(errs, fmt.Errorf("attempted decryption failed for %s: %w", base.name, err))
	}

	// This is good enough for now until we have better/distinct errors
	errMessage := "decryption failed for all provided methods: "
	sep := ""
	for _, err := range errs {
		errMessage += err.Error() + sep
		sep = "\n"
	}
	return nil, StatusUnknown, errors.New(errMessage)
}
Repository: opentofu/opentofu
File: internal/command/jsonplan/values_test.go (Go)

Code before:
}

func testSchemas() *tofu.Schemas {
	return &tofu.Schemas{
		Providers: map[addrs.Provider]providers.ProviderSchema{
			addrs.NewDefaultProvider("test"): providers.ProviderSchema{
				ResourceTypes: map[string]providers.Schema{
					"test_thing": {
						Version: 1,
						Block: &configschema.Block{
							Attributes: map[string]*configschema.Attribute{
								"woozles": {Type: cty.String, Optional: true, Computed: true},
								"foozles": {Type: cty.String, Optional: true},
							},
						},
					},
				},
			},
		},
	}
}

func testChanges(changes *plans.Changes) map[string]*plans.ResourceInstanceChangeSrc {
	ret := make(map[string]*plans.ResourceInstanceChangeSrc)
	for _, resource := range changes.Resources {
		if resource.Action != plans.Delete && resource.DeposedKey == states.NotDeposed {
			ret[resource.Addr.String()] = resource
		}
	}
	return ret
}

func testResourceAddrs() []addrs.AbsResourceInstance {
	return []addrs.AbsResourceInstance{
		mustAddr("test_thing.example"),
	}
}

func mustAddr(str string) addrs.AbsResourceInstance {
	addr, diags := addrs.ParseAbsResourceInstanceStr(str)
	if diags.HasErrors() {
		panic(diags.Err())
	}
	return addr
}


Review comment (suggestion):
```suggestion
		if resource.DeposedKey == states.NotDeposed {
```

Code after:
}

func testSchemas() *tofu.Schemas {
	return &tofu.Schemas{
		Providers: map[addrs.Provider]providers.ProviderSchema{
			addrs.NewDefaultProvider("test"): providers.ProviderSchema{
				ResourceTypes: map[string]providers.Schema{
					"test_thing": {
						Version: 1,
						Block: &configschema.Block{
							Attributes: map[string]*configschema.Attribute{
								"woozles": {Type: cty.String, Optional: true, Computed: true},
								"foozles": {Type: cty.String, Optional: true},
							},
						},
					},
				},
			},
		},
	}
}

func testChanges(changes *plans.Changes) map[string]*plans.ResourceInstanceChangeSrc {
	ret := make(map[string]*plans.ResourceInstanceChangeSrc)
	for _, resource := range changes.Resources {
		if resource.DeposedKey == states.NotDeposed {
			ret[resource.Addr.String()] = resource
		}
	}
	return ret
}

func testResourceAddrs() []addrs.AbsResourceInstance {
	return []addrs.AbsResourceInstance{
		mustAddr("test_thing.example"),
	}
}

func mustAddr(str string) addrs.AbsResourceInstance {
	addr, diags := addrs.ParseAbsResourceInstanceStr(str)
	if diags.HasErrors() {
		panic(diags.Err())
	}
	return addr
}
Repository: opentofu/opentofu
File: internal/configs/provider_meta.go (Go)

Code before:
import "github.com/hashicorp/hcl/v2"

// ProviderMeta represents a "provider_meta" block inside a "terraform" block
// in a module or file.
type ProviderMeta struct {
	Provider string
	Config   hcl.Body

	ProviderRange hcl.Range
	DeclRange     hcl.Range
}

func decodeProviderMetaBlock(block *hcl.Block) (*ProviderMeta, hcl.Diagnostics) {
	// provider_meta must be a static map. We can verify this by attempting to
	// evaluate the values.
	attrs, diags := block.Body.JustAttributes()
	if diags.HasErrors() {
		return nil, diags
	}

	for _, attr := range attrs {
		_, d := attr.Expr.Value(nil)
		diags = append(diags, d...)
	}

	// verify that the local name is already localized or produce an error.
	if diags = append(diags, checkProviderNameNormalized(block.Labels[0], block.DefRange)...); diags.HasErrors() {
		return nil, diags
	}

	return &ProviderMeta{
		Provider:      block.Labels[0],
		ProviderRange: block.LabelRanges[0],
		Config:        block.Body,
		DeclRange:     block.DefRange,
	}, diags
}


Review comment (suggestion):
This comment should be updated to reflect that it's no longer throwing an error but instead returning early.

Code after:
import "github.com/hashicorp/hcl/v2"

// ProviderMeta represents a "provider_meta" block inside a "terraform" block
// in a module or file.
type ProviderMeta struct {
	Provider string
	Config   hcl.Body

	ProviderRange hcl.Range
	DeclRange     hcl.Range
}

func decodeProviderMetaBlock(block *hcl.Block) (*ProviderMeta, hcl.Diagnostics) {
	// provider_meta must be a static map. We can verify this by attempting to
	// evaluate the values.
	attrs, diags := block.Body.JustAttributes()
	if diags.HasErrors() {
		return nil, diags
	}

	for _, attr := range attrs {
		_, d := attr.Expr.Value(nil)
		diags = append(diags, d...)
	}

	// If the name is invalid, we return an error early, lest the invalid value
	// is used by the caller and causes a panic further down the line.
	if diags = append(diags, checkProviderNameNormalized(block.Labels[0], block.DefRange)...); diags.HasErrors() {
		return nil, diags
	}

	return &ProviderMeta{
		Provider:      block.Labels[0],
		ProviderRange: block.LabelRanges[0],
		Config:        block.Body,
		DeclRange:     block.DefRange,
	}, diags
}
Repository: opentofu/opentofu
File: internal/backend/remote-state/http/client.go (Go)

Code before:
			return "", &statemgr.LockError{
				Info: info,
				Err:  fmt.Errorf("HTTP remote state already locked, failed to unmarshal body"),
			}
		}
		return "", &statemgr.LockError{
			Info: &existing,
			Err:  fmt.Errorf("HTTP remote state already locked: ID=%s", existing.ID),
		}
	default:
		return "", fmt.Errorf("Unexpected HTTP response code %d", resp.StatusCode)
	}
}

func (c *httpClient) Unlock(id string) error {
	if c.UnlockURL == nil {
		return nil
	}

	var lockInfo statemgr.LockInfo

	// force unlock command does not instantiate statemgr.LockInfo
	// which means that c.jsonLockInfo will be nil
	if c.jsonLockInfo != nil {
		if err := json.Unmarshal(c.jsonLockInfo, &lockInfo); err != nil {
			return fmt.Errorf("failed to unmarshal jsonLockInfo")
		}
		if lockInfo.ID != id {
			return &statemgr.LockError{
				Info: &lockInfo,
				Err:  fmt.Errorf("lock id %q does not match existing lock", id),
			}
		}
	}

	lockInfo.ID = id

	resp, err := c.httpRequest(c.UnlockMethod, c.UnlockURL, lockInfo.Marshal(), "unlock")
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK:
		return nil
	default:
		return fmt.Errorf("Unexpected HTTP response code %d", resp.StatusCode)
	}
}


Review comment (suggestion):
We should probably include the err as `%w` in the fmt.Errorf here.

Code after:
			return "", &statemgr.LockError{
				Info: info,
				Err:  fmt.Errorf("HTTP remote state already locked, failed to unmarshal body"),
			}
		}
		return "", &statemgr.LockError{
			Info: &existing,
			Err:  fmt.Errorf("HTTP remote state already locked: ID=%s", existing.ID),
		}
	default:
		return "", fmt.Errorf("Unexpected HTTP response code %d", resp.StatusCode)
	}
}

func (c *httpClient) Unlock(id string) error {
	if c.UnlockURL == nil {
		return nil
	}

	var lockInfo statemgr.LockInfo

	// force unlock command does not instantiate statemgr.LockInfo
	// which means that c.jsonLockInfo will be nil
	if c.jsonLockInfo != nil {
		if err := json.Unmarshal(c.jsonLockInfo, &lockInfo); err != nil { //nolint:musttag // for now add musttag until we fully adopt the linting rules
			return fmt.Errorf("failed to unmarshal jsonLockInfo: %w", err)
		}
		if lockInfo.ID != id {
			return &statemgr.LockError{
				Info: &lockInfo,
				Err:  fmt.Errorf("lock id %q does not match existing lock", id),
			}
		}
	}

	lockInfo.ID = id

	resp, err := c.httpRequest(c.UnlockMethod, c.UnlockURL, lockInfo.Marshal(), "unlock")
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK:
		return nil
	default:
		return fmt.Errorf("Unexpected HTTP response code %d", resp.StatusCode)
	}
}
Repository: opentofu/opentofu
File: internal/tofu/context_validate_test.go (Go)

Code before:
	m := testModuleInline(t, map[string]string{
		"main.tf": `
resource "aws_instance" "test" {
}
locals {
  deprecated = aws_instance.test.foo
}

 `,
	})

	ctx := testContext2(t, &ContextOpts{
		Providers: map[addrs.Provider]providers.Factory{
			addrs.NewDefaultProvider("aws"): testProviderFuncFixed(p),
		},
	})

	diags := ctx.Validate(context.Background(), m)
	warn := diags.ErrWithWarnings().Error()
	if !strings.Contains(warn, `The attribute "foo" is deprecated`) {
		t.Fatalf("expected deprecated warning, got: %q\n", warn)
	}
}

// Ensure that the plantimestamp() call is not affecting the validation step.
func TestContext2Validate_range_over_zero_plan_timestamp(t *testing.T) {
	p := testProvider("test")

	m := testModule(t, "plan_range_over_plan_timestamp")

	ctx := testContext2(t, &ContextOpts{
		Providers: map[addrs.Provider]providers.Factory{
			addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
		},
	})

	diags := ctx.Validate(context.Background(), m)
	if diags.HasErrors() {
		t.Fatal(diags.ErrWithWarnings())
	}
}


Review comment (suggestion):
nit: I am a bit confused by the naming in this file, however I believe it should be:

```suggestion
func TestContext2Validate_rangeOverZeroPlanTimestamp(t *testing.T) {
```

Code after:
	m := testModuleInline(t, map[string]string{
		"main.tf": `
resource "aws_instance" "test" {
}
locals {
  deprecated = aws_instance.test.foo
}

 `,
	})

	ctx := testContext2(t, &ContextOpts{
		Providers: map[addrs.Provider]providers.Factory{
			addrs.NewDefaultProvider("aws"): testProviderFuncFixed(p),
		},
	})

	diags := ctx.Validate(context.Background(), m)
	warn := diags.ErrWithWarnings().Error()
	if !strings.Contains(warn, `The attribute "foo" is deprecated`) {
		t.Fatalf("expected deprecated warning, got: %q\n", warn)
	}
}

// Ensure that the plantimestamp() call is not affecting the validation step.
func TestContext2Validate_rangeOverZeroPlanTimestamp(t *testing.T) {
	p := testProvider("test")

	m := testModule(t, "plan_range_over_plan_timestamp")

	ctx := testContext2(t, &ContextOpts{
		Providers: map[addrs.Provider]providers.Factory{
			addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
		},
	})

	diags := ctx.Validate(context.Background(), m)
	if diags.HasErrors() {
		t.Fatal(diags.ErrWithWarnings())
	}
}